资料来源 : http://github.ibireme.com/github/list/ios
GitHub : 链接地址
简介 :
A delightful iOS and OS X networking framework.
推荐参考 :
http://www.aiuxian.com/article/p-1537192.html
链接地址一、 文件目录
链接地址1. AFNetworking 目录内容
链接地址2. UIKit+AFNetworking 目录内容
链接地址3. 关联关系(AFNetworking)
链接地址二、 详细介绍
链接地址1. AFNetworking
这是 AFNetworking 的主要部分,包括 6 个功能部分共 9 个类。
链接地址1)AFNetworking.h
- #import <Foundation/Foundation.h>
- #import <Availability.h>
- #ifndef _AFNETWORKING_
- #define _AFNETWORKING_
- #import "AFURLRequestSerialization.h"
- #import "AFURLResponseSerialization.h"
- #import "AFSecurityPolicy.h"
- #import "AFNetworkReachabilityManager.h"
- #import "AFURLConnectionOperation.h"
- #import "AFHTTPRequestOperation.h"
- #import "AFHTTPRequestOperationManager.h"
- #if ( ( defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || \
- ( defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 ) )
- #import "AFURLSessionManager.h"
- #import "AFHTTPSessionManager.h"
- #endif
- #endif /* _AFNETWORKING_ */
这是 AFNetworking 的公共头文件,在使用 AFNetworking 库时可直接在 Prefix.pch 文件中引入,或者在工程的网络管理模块相关文件中引入。
链接地址2)AFSecurityPolicy.h
- /**
- `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections.
- Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled.
- */
- @interface AFSecurityPolicy : NSObject
- /**
- The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`.
- */
- @property (nonatomic, assign) AFSSLPinningMode SSLPinningMode;
- /**
- Whether to evaluate an entire SSL certificate chain, or just the leaf certificate. Defaults to `YES`.
- */
- @property (nonatomic, assign) BOOL validatesCertificateChain;
- /**
- The certificates used to evaluate server trust according to the SSL pinning mode. By default, this property is set to any (`.cer`) certificates included in the app bundle.
- */
- @property (nonatomic, strong) NSArray *pinnedCertificates;
- /**
- Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`.
- */
- @property (nonatomic, assign) BOOL allowInvalidCertificates;
- /**
- Whether or not to validate the domain name in the certificates CN field. Defaults to `YES` for `AFSSLPinningModePublicKey` or `AFSSLPinningModeCertificate`, otherwise `NO`.
- */
- @property (nonatomic, assign) BOOL validatesDomainName;
这个类主要是为网络请求添加 SSL 安全验证, SSL 安全验证类型有如下三种,默认是 AFSSLPinningModeNone 类型,另外通过 SSL 证书和密钥可以增加请求的安全性,避免请求被劫持和攻击。
- typedef NS_ENUM(NSUInteger, AFSSLPinningMode) {
- AFSSLPinningModeNone,
- AFSSLPinningModePublicKey,
- AFSSLPinningModeCertificate,
- };
关于 SSL 和数字证书相关可参考这里(SSL)和这里(数字证书)。
链接地址3)AFNetworkReachabilityManager.h
- /**
- `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
- See Apple's Reachability Sample Code (https://developer.apple.com/library/ios/samplecode/reachability/)
- @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined.
- */
- @interface AFNetworkReachabilityManager : NSObject
- /**
- The current network reachability status.
- */
- @property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
- /**
- Whether or not the network is currently reachable.
- */
- @property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable;
- /**
- Whether or not the network is currently reachable via WWAN.
- */
- @property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN;
- /**
- Whether or not the network is currently reachable via WiFi.
- */
- @property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi;
这个类和苹果官方提供的 Reachability 类功能类似,但是功能更加强大,不仅增加了更多的公共属性,也增加了状态变更闭包(block)操作,还增加了通知标志串,用过 Reachability 应该能够很快理解并爱上这个类。
链接地址4)AFURLConnectionOperation.h
- @interface AFURLConnectionOperation : NSOperation <NSURLConnectionDelegate, NSURLConnectionDataDelegate, NSCoding, NSCopying>
- ///-------------------------------
- /// @name Accessing Run Loop Modes
- ///-------------------------------
- /**
- The run loop modes in which the operation will run on the network thread. By default, this is a single-member set containing `NSRunLoopCommonModes`.
- */
- @property (nonatomic, strong) NSSet *runLoopModes;
- ///-----------------------------------------
- /// @name Getting URL Connection Information
- ///-----------------------------------------
- /**
- The request used by the operation's connection.
- */
- @property (readonly, nonatomic, strong) NSURLRequest *request;
- /**
- The last response received by the operation's connection.
- */
- @property (readonly, nonatomic, strong) NSURLResponse *response;
- /**
- The error, if any, that occurred in the lifecycle of the request.
- */
- @property (readonly, nonatomic, strong) NSError *error;
- ///----------------------------
- /// @name Getting Response Data
- ///----------------------------
- /**
- The data received during the request.
- */
- @property (readonly, nonatomic, strong) NSData *responseData;
- /**
- The string representation of the response data.
- */
- @property (readonly, nonatomic, copy) NSString *responseString;
- /**
- The string encoding of the response.
- If the response does not specify a valid string encoding, `responseStringEncoding` will return `NSUTF8StringEncoding`.
- */
- @property (readonly, nonatomic, assign) NSStringEncoding responseStringEncoding;
- ///-------------------------------
- /// @name Managing URL Credentials
- ///-------------------------------
- /**
- Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default.
- This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`.
- */
- @property (nonatomic, assign) BOOL shouldUseCredentialStorage;
- /**
- The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`.
- This will be overridden by any shared credentials that exist for the username or password of the request URL, if present.
- */
- @property (nonatomic, strong) NSURLCredential *credential;
- ///-------------------------------
- /// @name Managing Security Policy
- ///-------------------------------
- /**
- The security policy used to evaluate server trust for secure connections.
- */
- @property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
- ///------------------------
- /// @name Accessing Streams
- ///------------------------
- /**
- The input stream used to read data to be sent during the request.
- This property acts as a proxy to the `HTTPBodyStream` property of `request`.
- */
- @property (nonatomic, strong) NSInputStream *inputStream;
- /**
- The output stream that is used to write data received until the request is finished.
- By default, data is accumulated into a buffer that is stored into `responseData` upon completion of the request. When `outputStream` is set, the data will not be accumulated into an internal buffer, and as a result, the `responseData` property of the completed request will be `nil`. The output stream will be scheduled in the network thread runloop upon being set.
- */
- @property (nonatomic, strong) NSOutputStream *outputStream;
- ///---------------------------------
- /// @name Managing Callback Queues
- ///---------------------------------
- /**
- The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used.
- */
- @property (nonatomic, strong) dispatch_queue_t completionQueue;
- /**
- The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used.
- */
- @property (nonatomic, strong) dispatch_group_t completionGroup;
- ///---------------------------------------------
- /// @name Managing Request Operation Information
- ///---------------------------------------------
- /**
- The user info dictionary for the receiver.
- */
- @property (nonatomic, strong) NSDictionary *userInfo;
这是一个 NSOperation 子类,它实现了 NSURLConnection 的全部代理方法,所执行的是单个网络请求的操作。
链接地址5)AFHTTPRequestOperation.h
- /**
- `AFHTTPRequestOperation` is a subclass of `AFURLConnectionOperation` for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.
- */
- @interface AFHTTPRequestOperation : AFURLConnectionOperation
- ///------------------------------------------------
- /// @name Getting HTTP URL Connection Information
- ///------------------------------------------------
- /**
- The last HTTP response received by the operation's connection.
- */
- @property (readonly, nonatomic, strong) NSHTTPURLResponse *response;
- /**
- Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an AFHTTPResponse serializer, which uses the raw data as its response object. The serializer validates the status code to be in the `2XX` range, denoting success. If the response serializer generates an error in `-responseObjectForResponse:data:error:`, the `failure` callback of the session task or request operation will be executed; otherwise, the `success` callback will be executed.
- @warning `responseSerializer` must not be `nil`. Setting a response serializer will clear out any cached value
- */
- @property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
- /**
- An object constructed by the `responseSerializer` from the response and response data. Returns `nil` unless the operation `isFinished`, has a `response`, and has `responseData` with non-zero content length. If an error occurs during serialization, `nil` will be returned, and the `error` property will be populated with the serialization error.
- */
- @property (readonly, nonatomic, strong) id responseObject;
这是 AFURLConnectionOperation 的子类,主要针对 HTTP 和 HTTPS 类型的请求,这也是最常用的请求操作。
链接地址6)AFHTTPRequestOperationManager.h
- @interface AFHTTPRequestOperationManager : NSObject <NSCoding, NSCopying>
- /**
- The URL used to monitor reachability, and construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods.
- */
- @property (readonly, nonatomic, strong) NSURL *baseURL;
- /**
- Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `AFHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies.
- @warning `requestSerializer` must not be `nil`.
- */
- @property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer;
- /**
- Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to a JSON serializer, which serializes data from responses with a `application/json` MIME type, and falls back to the raw data object. The serializer validates the status code to be in the `2XX` range, denoting success. If the response serializer generates an error in `-responseObjectForResponse:data:error:`, the `failure` callback of the session task or request operation will be executed; otherwise, the `success` callback will be executed.
- @warning `responseSerializer` must not be `nil`.
- */
- @property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
- /**
- The operation queue on which request operations are scheduled and run.
- */
- @property (nonatomic, strong) NSOperationQueue *operationQueue;
- ///-------------------------------
- /// @name Managing URL Credentials
- ///-------------------------------
- /**
- Whether request operations should consult the credential storage for authenticating the connection. `YES` by default.
- @see AFURLConnectionOperation -shouldUseCredentialStorage
- */
- @property (nonatomic, assign) BOOL shouldUseCredentialStorage;
- /**
- The credential used by request operations for authentication challenges.
- @see AFURLConnectionOperation -credential
- */
- @property (nonatomic, strong) NSURLCredential *credential;
- ///-------------------------------
- /// @name Managing Security Policy
- ///-------------------------------
- /**
- The security policy used by created request operations to evaluate server trust for secure connections. `AFHTTPRequestOperationManager` uses the `defaultPolicy` unless otherwise specified.
- */
- @property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
- ///------------------------------------
- /// @name Managing Network Reachability
- ///------------------------------------
- /**
- The network reachability manager. `AFHTTPRequestOperationManager` uses the `sharedManager` by default.
- */
- @property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
这是 AFHTTPRequestOperation 的一个管理类,细化了不同类型的请求操作( GET、HEAD、POST、PUT、PATCH、DELETE ),通过这个管理类创建的网络请求操作都会被加入到 operationQueue 中执行。
链接地址7)AFURLSessionManager.h
- @interface AFURLSessionManager : NSObject <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate, NSCoding, NSCopying>
- /**
- The managed session.
- */
- @property (readonly, nonatomic, strong) NSURLSession *session;
- /**
- The operation queue on which delegate callbacks are run.
- */
- @property (readonly, nonatomic, strong) NSOperationQueue *operationQueue;
- /**
- Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`.
- @warning `responseSerializer` must not be `nil`.
- */
- @property (nonatomic, strong) id <AFURLResponseSerialization> responseSerializer;
- ///-------------------------------
- /// @name Managing Security Policy
- ///-------------------------------
- /**
- The security policy used by created request operations to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified.
- */
- @property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
- ///--------------------------------------
- /// @name Monitoring Network Reachability
- ///--------------------------------------
- /**
- The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default.
- */
- @property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
- ///----------------------------
- /// @name Getting Session Tasks
- ///----------------------------
- /**
- The data, upload, and download tasks currently run by the managed session.
- */
- @property (readonly, nonatomic, strong) NSArray *tasks;
- /**
- The data tasks currently run by the managed session.
- */
- @property (readonly, nonatomic, strong) NSArray *dataTasks;
- /**
- The upload tasks currently run by the managed session.
- */
- @property (readonly, nonatomic, strong) NSArray *uploadTasks;
- /**
- The download tasks currently run by the managed session.
- */
- @property (readonly, nonatomic, strong) NSArray *downloadTasks;
- ///---------------------------------
- /// @name Managing Callback Queues
- ///---------------------------------
- /**
- The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used.
- */
- @property (nonatomic, strong) dispatch_queue_t completionQueue;
- /**
- The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used.
- */
- @property (nonatomic, strong) dispatch_group_t completionGroup;
这是 AFNetworking 实现的 NSURLSession 的一个管理类,在这个类里面已经实现了全部相关的 NSURLSession 代理方法,NSURLSession 是 iOS7 新增加的用于网络请求相关的任务类,具体可参考 这里(苹果官方文档) 、 这里(相关博客一) 和 这里(相关博客二) 。
链接地址8)AFHTTPSessionManager.h
- @interface AFHTTPSessionManager : AFURLSessionManager <NSCoding, NSCopying>
- /**
- The URL used to monitor reachability, and construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods.
- */
- @property (readonly, nonatomic, strong) NSURL *baseURL;
- /**
- Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `AFHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies.
- @warning `requestSerializer` must not be `nil`.
- */
- @property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer;
- /**
- Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`.
- @warning `responseSerializer` must not be `nil`.
- */
- @property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
这是 AFURLSessionManager 的一个管理类,针对 HTTP 细化了不同类型的请求操作( GET、HEAD、POST、PUT、PATCH、DELETE ),因为 NSURLSession 是 iOS7 新增加的用于网络请求相关的任务类,所以仅针对 iOS7 系统时可考虑优先使用这个管理类替代 AFHTTPRequestOperationManager ,如果需要考虑向前兼容,还是需要使用 AFHTTPRequestOperationManager 。
链接地址9)AFURLRequestSerialization.h
这个文件主要定义了一些用于网络请求的协议和类,其中包括了请求格式、请求参数以及相关请求设置的方法。
链接地址10)AFURLResponseSerialization.h
这个文件主要定义了一些网络返回数据格式以及解析的协议和类,包括JSON、XML、Image等格式的返回数据获取和格式解析等。
链接地址2. UIKit+AFNetworking
这是 AFNetworking 针对 UIKit 部分系统控件做的类别扩展,包括 1 个管理类定义和 8 个类别扩展。
链接地址1)UIKit+AFNetworking.h
- #import <UIKit/UIKit.h>
- #ifndef _UIKIT_AFNETWORKING_
- #define _UIKIT_AFNETWORKING_
- #import "AFNetworkActivityIndicatorManager.h"
- #import "UIActivityIndicatorView+AFNetworking.h"
- #import "UIAlertView+AFNetworking.h"
- #import "UIButton+AFNetworking.h"
- #import "UIImageView+AFNetworking.h"
- #import "UIKit+AFNetworking.h"
- #import "UIProgressView+AFNetworking.h"
- #import "UIWebView+AFNetworking.h"
- #endif /* _UIKIT_AFNETWORKING_ */
这是 UIKit+AFNetworking 的公共头文件,如果需要使用 AFNetworking 的 UIKit 扩展时可直接在 Prefix.pch 文件中引入,或者在工程的相关文件中引入。
链接地址2)AFNetworkActivityIndicatorManager.h
- @interface AFNetworkActivityIndicatorManager : NSObject
- /**
- A Boolean value indicating whether the manager is enabled.
- If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO.
- */
- @property (nonatomic, assign, getter = isEnabled) BOOL enabled;
- /**
- A Boolean value indicating whether the network activity indicator is currently displayed in the status bar.
- */
- @property (readonly, nonatomic, assign) BOOL isNetworkActivityIndicatorVisible;
这个类主要是为了自动显示和隐藏请求时的状态提示,如果你确实需要它的话用这个类还是很方便的,使用方法也很简单。只要在 AppDelegate application:didFinishLaunchingWithOptions: 方法中添加一句
- [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
就可以了,之后在使用 AFNetworking 发起请求和终止请求时都会自动显示和隐藏状态提示。
链接地址3)UIActivityIndicatorView+AFNetworking.h
- #import <Foundation/Foundation.h>
- #import <Availability.h>
- #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
- #import <UIKit/UIKit.h>
- @class AFURLConnectionOperation;
- /**
- This category adds methods to the UIKit framework's `UIActivityIndicatorView` class. The methods in this category provide support for automatically starting and stopping animation depending on the loading state of a request operation or session task.
- */
- @interface UIActivityIndicatorView (AFNetworking)
- ///----------------------------------
- /// @name Animating for Session Tasks
- ///----------------------------------
- /**
- Binds the animating state to the state of the specified task.
- @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled.
- */
- #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
- - (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task;
- #endif
- ///---------------------------------------
- /// @name Animating for Request Operations
- ///---------------------------------------
- /**
- Binds the animating state to the execution state of the specified operation.
- @param operation The operation. If `nil`, automatic updating from any previously specified operation will be disabled.
- */
- - (void)setAnimatingWithStateOfOperation:(AFURLConnectionOperation *)operation;
- @end
这个类别为网络请求的状态显示增加了两个方法,通过这两个方法可以根据当前任务的状态或操作的状态决定网络请求状态的显示与隐藏。
链接地址4)UIAlertView+AFNetworking.h
和上面的类别类似,不过这个类别主要是为 UIAlertView 增加了几个方法,当相关的网络任务和请求操作发生错误时,会弹出一个 UIAlertView ,虽然 iOS7 的 UIAlertView 看上去温柔很多,很我个人还是很讨厌这个粗暴的弹出提示,我同样不喜欢转圈圈的等待提示。
链接地址5)UIButton+AFNetworking.h
这个类别主要是为 UIButton 增加了异步获取网络图片的类别方法,用过类似 EGOImageView 的应该很容易理解。
链接地址6)UIImageView+AFNetworking.h
说曹操曹操到,这个就是 EGOImageView 的 AFNetworking 版。
链接地址7)UIProgressView+AFNetworking.h
同 UIActivityIndicatorView+AFNetworking ,只是这个类别是针对 UIProgressView 的。
链接地址8)UIRefreshControl+AFNetworking.h
同 UIActivityIndicatorView+AFNetworking ,只是这个类别是针对 UIRefreshControl 的。UIRefreshControl 是 iOS7 新增加的下拉刷新显示控件,通过这个类别可以根据网络的行为和请求结果决定 UIRefreshControl 的显示状态。
链接地址9)UIWebView+AFNetworking.h
为 UIWebView 的载入请求增加了几个类别方法,便于决定请求成功失败如何显示,以及请求过程中等待状态的显示等。
链接地址三、 一点总结
粗略的浏览完 AFNetworking 的源代码之后深刻的感受了一下那么一句话:“我们不生产代码,我们只是 Github 的搬运工!”。自省一下,继续努力!
相关链接: