IOS network-05-AFNetwoking principle and Common Operations
Six modules of AFN
NSURLConnection further encapsulates NSURLConnection, including the following core classes:
AFURLConnectionOperation AFHTTPRequestOperationManager AFHTTPRequestOperation NSURLSession, the main object NSURLSession is further encapsulated, including the following core classes:
AFURLSessionManager AFHTTPSessionManager Reachability provides operation interfaces related to the network status, including the following core classes:
AFNetworkReachabilityManager Security provides Security-related operation interfaces, including the following core classes:
AFSecurityPolicy Serialization provides operation interfaces related to data parsing, including the following core classes:
AFURLRequestSerialization AFURLResponseSerialization UIKit provides operation interfaces related to the UI display during a large number of network requests. It is usually used for prompts during network requests to make user interaction more friendly, includes the following core categories/classes:
Using UIActivityIndicatorView + AFNetworking UIAlertView + AFNetworking UIButton + AFNetworking UIImageView + AFNetworking UIKit + AFNetworking UIProgressView + AFNetworking UIRefreshControl + AFNetworking UIWebView + response
How to create a task
Common Task
-(NSURLSessionDataTask *) dataTaskWithRequest :( NSURLRequest *) request completionHandler :( void (^) (NSURLResponse * response, id responseObject, NSError * error) completionHandler/*** request: request object * completionHandler: Block for the request to complete the call * response: Server response Information * responseObject: data returned by the server * error: error message */
Upload task (
Upload different types of files
)
// 1. upload File-type data-(optional *) uploadTaskWithRequest :( NSURLRequest *) request fromFile :( NSURL *) fileURL progress :( NSProgress * _ autoreleasing *) progress completionHandler :( void (^) (NSURLResponse * response, id responseObject, NSError * error) completionHandler/*** fileURL: Path of the file to be uploaded * // 2. upload NSData-(optional *) uploadTaskWithRequest :( NSURLRequest *) request fromData :( NSData *) bodyData progress :( NSProgress * _ autoreleasing *) progress completionHandler :( void (^) (NSURLResponse * response, id responseObject, NSError * error) completionHandler/*** bodyData: file data to be uploaded * // 3. upload stream data-(upload *) uploadTaskWithStreamedRequest :( NSURLRequest *) request progress :( NSProgress * _ autoreleasing *) progress completionHandler :( void (^) (NSURLResponse * response, id responseObject, NSError * error) completionHandler/*** request: request object initialized through stream data */
Download task
// 1. normal download task-(NSURLSessionDownloadTask *) downloadTaskWithRequest :( NSURLRequest *) request progress :( NSProgress * _ autoreleasing *) progress destination :( NSURL * (^) (NSURL * targetPath, NSURLResponse * response) destination completionHandler :( void (^) (NSURLResponse * response, NSURL * filePath, NSError * error) completionHandler/*** progress: manages the download progress * destination: block * targetPath used to save data calls: Data Storage path * server response information * // 2. download tasks that support resumable download-(NSURLSessionDownloadTask *) progress :( NSData *) resumeData progress :( NSProgress * _ autoreleasing *) progress destination :( NSURL * (^) (NSURL * targetPath, NSURLResponse * response) destination completionHandler :( void (^) (NSURLResponse * response, NSURL * filePath, NSError * error) completionHandler/*** progress: manages the download progress * resumeData: resumable download information */
AFHTTPSessionManager Common attributes
BaseURL (NSURL *) is used to monitor network accessibility and create the request object requestSerializer (AFHTTPRequestSerializer *). It specifies the resolution format responseSerializer (AFHTTPResponseSerializer *) of the GET, HEAD, and DELETE request parameters *), used to specify the format of data returned by the server
Common Methods
Initialization
// 1. create AFHTTPSessionManager object + (instancetype) manager // 2. create the AFHTTPSessionManager object-(instancetype) initWithBaseURL :( NSURL *) url/*** initialize the AFHTTPSessionManager object based on the url */-(instancetype) initWithBaseURL :( NSURL *) url sessionConfiguration :( NSURLSessionConfiguration *) configuration/*** initialize the AFHTTPSessionManager object based on the url and configuration */
Request data
// 1. GET request-(NSURLSessionDataTask *) GET :( NSString *) URLString parameters :( id) parameters success :( void (^) (NSURLSessionDataTask * task, id responseObject) success failure :( void (^) (NSURLSessionDataTask * task, NSError * error) failure/*** URLString: Request Path * parameters: Request Parameter * success: Block * responseObject called when the request succeeds: data returned by the server * failure: Block * error: error message * // 2 called when the request fails. POST request-(NSURLSessionDataTask *) POST :( NSString *) URLString parameters :( id) parameters success :( void (^) (NSURLSessionDataTask * task, id responseObject) success failure :( void (^) (NSURLSessionDataTask * task, NSError * error) failure/*** parameter meaning is the same as GET request */-(NSURLSessionDataTask *) POST :( NSString *) URLString parameters :( id) parameters :( void (^) (id formData) block success :( void (^) (NSURLSessionDataTask * task, id responseObject) success failure :( void (^) (NSURLSessionDataTask * task, NSError * error) failure/*** block: used to create multiple data sources */
Request network data using AFN
Request data (XML/JSON)
Create an AFHTTPSessionManager object
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
Format of returned data to the server
// Return data manager. responseSerializer = [AFXMLParserResponseSerializer serializer] in XML format; // return data manager. responseSerializer = [AFJSONResponseSerializer serializer] In JSON format;
Set Request body (
Type: XML or JSON
)
// The Request body is generally specified by the server in the format of NSDictionary * params ={ @ username: @ account, @ pwd: @ password, @ type: @ XML/JSON };
Send request
[Manager GET: @ Request Path parameters: params success: ^ (NSURLSessionDataTask * task, id responseObject) {// responseObject: NSLog (@ successful request) returned by the server;} failure: ^ (NSURLSessionDataTask * task, NSError * error) {// error: error message NSLog (@ request failed);}];
Upload data
Create an AFHTTPSessionManager object
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
Create upload task
/** NSURLConnection based */[manager POST: @ Request Path parameters: @ {@ username: @ password constructingBodyWithBlock: ^ (id formData) {// set the file to be uploaded NSData * data = [NSData dataWithContentsOfFile: @ path of the file to be uploaded]; [formData appendPartWithFileData: data name: @ file fileName: @test.png mimeType: @ image/png];} success: ^ (NSURLSessionDataTask * task, id responseObject) {// uploaded successfully} failure: ^ (NSURLSessionDataTask * task, NSError * error) {// Upload Failed}];/** Based on NSURLSession */[manager uploadTaskWithRequest: request fromData: data progress: progress completionHandler: ^ (NSURLResponse * response, id responseObject, NSError * error) {// data uploaded successfully}];
Download data
Create an AFHTTPSessionManager object
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
Create download task
/** NSURLSession-based */[manager downloadTaskWithRequest: request progress: progress destination: ^ NSURL * (NSURL * targetPath, NSURLResponse * response) {// Block used to store the downloaded data} completionHandler: ^ (NSURLResponse * response, NSURL * filePath, NSError * error) {// Block called upon download completion}]
.