Six modules of AFN
-
Nsurlconnection, the main nsurlconnection is further encapsulated, containing the following core classes:
- Afurlconnectionoperation
- Afhttprequestoperationmanager
- Afhttprequestoperation
-
Nsurlsession, the main object of the Nsurlsession object is further encapsulated, containing the following core classes:
- Afurlsessionmanager
- Afhttpsessionmanager
-
Reachability, which provides the operating interface associated with the network state, contains the following core classes:
- Afnetworkreachabilitymanager
-
Security, which provides a safety-related operational interface, contains the following core classes:
-
serialization, which provides the operational interfaces associated with parsing data, contains the following core classes:
- Afurlrequestserialization
- Afurlresponseserialization
-
UIKit, which provides a large number of network requests in the process of UI interface display related to the interface, usually for the network request during the prompt, to make user interaction more friendly, including the following core categories/classes:
- Afnetworkactivityindicatormanager
- Uiactivityindicatorview+afnetworking
- Uialertview+afnetworking
- Uibutton+afnetworking
- Uiimageview+afnetworking
- Uikit+afnetworking
- Uiprogressview+afnetworking
- Uirefreshcontrol+afnetworking
- Uiwebview+afnetworking
Afurlsessionmanager
-
How to create a task
-
Common tasks
*)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler/*** request:请求对象* completionHandler:请求完成调用的Block * response:服务器的响应信息* responseObject:服务器返回的数据* error:错误信息*/
-
Upload Task ( 分别上传不同类型的文件 )
1. Upload data for file type-(nsurlsessionuploadtask*) Uploadtaskwithrequest: (nsurlrequest*) Request FromFile: (Nsurl*) FileURL Progress: (nsprogress* __autoreleasing*) Progress Completionhandler: (void (^) (nsurlresponse*response, id responseobject, nserror*error)) completionhandler/*** FileURL: The path of the file to be uploaded*///2. Upload NSData type of data-(nsurlsessionuploadtask*) 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-(nsurlsessionuploadtask *) Uploadtaskwithstreamedrequest: (NSURLRequest *) Request progress: (nsprogress * __autoreleasing *) Progress Completionhandler: (void (^) (nsurlresponse *response, ID Responseobject, Nserror *error)) Completionhandler/*** request: Requested object initialized via 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: Manage Download progress* Destination: block for saving data calls* TargetPath: Save path of data* Server Response information *///2. Download task to support breakpoint download-(nsurlsessiondownloadtask *) Downloadtaskwithresumedata: (NSData *) Resumedata Progress: (nsprogress * __autoreleasing *) Progress destination: (Nsurl * (^) (nsurl * TargetPath, Nsurlresponse *response)) Destination Completionhandler: (void (^) (nsurlresponse *response, Nsurl *filepath, Nserror *error)) Completionhandler/*** Progress: Manage Download Progress * Resumedata: Breakpoint Information When a breakpoint is downloaded * /
Afhttpsessionmanager
-
Common Properties
- BaseURL (Nsurl *) for monitoring network accessibility and creating request objects
- Requestserializer (Afhttprequestserializer *) specifying the parse format for the, and delete request parameters
- Responseserializer (Afhttpresponseserializer *) for specifying the format of the server return data
-
Common methods
-
Initialization
*)url/*** 根据url初始化AFHTTPSessionManager对象*/- (instancetype)initWithBaseURL:(NSURL *)url sessionConfiguration:(NSURLSessionConfiguration *)configuration/*** 根据url与configuration初始化AFHTTPSessionManager对象*/
-
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: the block* Responseobject called when the request was successful: data returned by the server * failure: Called when a request fails block* Error message */2. 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 same as GET request */-( Nsurlsessiondatatask *) POST: (nsstring *) urlstring parameters: (ID) parameters Constructingbodywithblock: ( void (^) (ID <AFMultipartFormData> formData)) block success: (void (^) (Nsurlsessiondatatask * Task, ID responseobject)) Success failure: (void (^) (nsurlsessiondatatask *task, nserror *error)) Failure/*** BLOCK: Used to create multiple data sources */
Using AFN to request network data
-
Request data (Xml/json)
-
Create a Afhttpsessionmanager object
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
-
Specify the return data format for the server
//以XML文档的形式返回数据manager.responseSerializer = [AFXMLParserResponseSerializer serializer];//以JSON形式返回数据manager.responseSerializer = [AFJSONResponseSerializer serializer];
-
Set the request body ( type is XML or JSON )
// The request body is typically specified by the server format nsdictionary *params = @{@ "user Name ": @" account ", @" pwd ": @" password ", @" type ": @" Xml/json "};
-
Send Request
[manager GET:@"请求路径" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {//responseObject:服务器返回的数据 NSLog(@"请求成功");} failure:^(NSURLSessionDataTask *task, NSError *error) {//error:错误信息 NSLog(@"请求失败");}];
-
Uploading data
-
Create a Afhttpsessionmanager object
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
-
Create an upload task
/** based on Nsurlconnection*/[managerpost:@"Request Path"parameters:@{@"User name": @Passwordconstructingbodywithblock:^ (id<afmultipartformdata> formData) {Set up files that need to be uploaded nsdata *data = [NSDatadatawithcontentsoffile:@"Path to the long-passing file"]; [FormDataappendpartwithfiledata:data name:@ "file" filename:@ "test.png" mimetype:@ "Image/png"];} success:^ (nsurlsessiondatatask *task, id responseobject) {//upload succeeded} failure:^ (nsurlsessiondatatask *task, NSError *error {//upload failed}]; /** based on Nsurlsession*/[manager uploadtaskwithrequest:request Span class= "hljs-string" >fromdata:data progress:progress completionhandler:^ (nsurlresponse *response, id responseobject, Nserror *error) {//upload data successfully }];
-
Download data
-
Create a Afhttpsessionmanager object
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
-
Create a download task
/**基于NSURLSession*/[manager downloadTaskWithRequest:request progress:progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { // 存储下载数据是调用的Block} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { //下载完成时调用的Block}]
Lan Yi IOS afnetwoking principle and common operation