Use of iOS network access afnetworking
Afnetworking is a popular third-party network access Library on iOS, and we can download it on GitHub, with its detailed instructions on GitHub, and the latest AFNetworing2.0 and 1.0, which are only a summary of the 2.0 commonly used methods.
Nsurlconnection-based API
Submit a GET Request
Afhttprequestoperationmanager *manager = [Afhttprequestoperationmanager manager];
[Manager get:@ "Http://example.com/resources.json" Parameters:nil success:^ (afhttprequestoperation *operation, ID Responseobject) {
NSLog (@ "JSON:%@", responseobject);
} failure:^ (Afhttprequestoperation *operation, Nserror *error) {
NSLog (@ "error:%@", error);
}];
Afresponseserializer
In the code above, Responseobject represents the returned value, and when the network returns data such as JSON or XML, they are essentially strings, and we need to do something to turn the string into the desired object. Afnetworking do these things for us by setting the Responseserializer property of the Afhttprequestoperationmanager object.
If the data is returned in JSON format, then we set
Manager.responseserializer = [[Afjsonresponseserializer alloc] init], Responseobject is the root object of the obtained JSON (nsdictionary or Nsarray)
If the plist format is returned, we'll use the Afpropertylistresponseserializer parser.
If the XML format is returned, we use the Afxmlparserresponseserializer parser, Responseobject represents the Nsxmlparser
If you are returning a picture, you can use the Afimageresponseserializer
If you just want to get the return binary format, you can use the Afhttpresponseserializer
Afrequestserializer
Afhttprequestoperationmanager can also set the requested format by setting the Requestseializer property
Like the following request address and parameters
NSString *urlstring = @ "http://example.com";
Nsdictionary *parameters = @{@ "foo": @ "bar" @ "baz": @[@1, @2, @3]};
We use the Get submission method of Afhttprequestserializer
[[Afhttprequestserializer Serializer] requestwithmethod:@ "GET" urlstring:urlstring parameters:parameters Error:nil] ;
GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3
We use the Afhttprequestserializer Post submission method
[[Afhttprequestserializer Serializer] requestwithmethod:@ "POST" urlstring:urlstring parameters:parameters];
POST http://example.com/
content-type:application/x-www-form-urlencoded
Foo=bar&baz[]=1&baz[]=2&baz[]=3
We use Afjsonrequestserializer
[[Afjsonrequestserializer Serializer] requestwithmethod:@ "POST" urlstring:urlstring parameters:parameters];
POST http://example.com/
Content-type:application/json
{"foo": "Bar", "baz": [All-in-all]}
The data for the default commit request is binary (Afhttprequestserializer) and the return format is JSON (Afjsonresponseserializer)
Submit a POST request
Afhttprequestoperationmanager *manager = [Afhttprequestoperationmanager manager]; Nsdictionary *parameters = @{@ "foo": @ "bar"}; [Manager post:@ "Http://example.com/resources.json" Parameters:parameters success:^ (Afhttprequestoperation * operation, id responseobject) { NSLog (@ "JSON:%@", responseobject); } failure:^ (Afhttprequestoperation *operation, Nserror *error) { NSLog (@ "error:%@", error); }]; |
File included when submitting a POST request
Afhttprequestoperationmanager *manager = [Afhttprequestoperationmanager manager]; Nsdictionary *parameters = @{@ "foo": @ "bar"}; Nsurl *filepath = [Nsurl fileurlwithpath:@ "File://path/to/image.png"]; [Manager post:@ "Http://example.com/resources.json" Parameters:parameters constructingbodywithblock:^ (id< Afmultipartformdata> formData) { [FormData appendpartwithfileurl:filepath name:@ "image" Error:nil]; } success:^ (afhttprequestoperation *operation, id responseobject) { NSLog (@ "Success:%@", responseobject); } failure:^ (Afhttprequestoperation *operation, Nserror *error) { NSLog (@ "error:%@", error); }]; |
You can also upload nsdata data files via Appendpartwithfiledata.
Afhttprequestoperation
In addition to accessing the network using Afhttprequestoperationmanager, you can also use the Afhttprequestoperation Afhttprequestoperation inherits from Afurlconnectionoperation,
Afurlconnectionoperation inherits from Nsoperation, so a network request task can be defined by afhttprequestoperation and then added to the queue for execution.
Nsmutablearray *mutableoperations = [Nsmutablearray array]; For (Nsurl *fileurl in filestoupload) { Nsurlrequest *request = [[Afhttprequestserializer serializer] multipartformrequestwithmethod:@ "POST" URLString:@ " Http://example.com/upload "Parameters:nil constructingbodywithblock:^ (id<afmultipartformdata> formData) { [FormData appendpartwithfileurl:fileurl name:@ "images[]" error:nil]; }]; Afhttprequestoperation *operation = [[Afhttprequestoperation alloc] initwithrequest:request]; [Mutableoperations addobject:operation]; } Nsarray *operations = [afurlconnectionoperation batchofrequestoperations:@[...] progressblock:^ (NSUInteger Numberoffinishedoperations, Nsuinteger totalnumberofoperations) { NSLog (@ "%lu of%lu Complete", numberoffinishedoperations, totalnumberofoperations); } completionblock:^ (Nsarray *operations) { NSLog (@ "All operations with batch complete"); }]; [[Nsoperationqueue Mainqueue] addoperations:operations Waituntilfinished:no]; |
Bulk task Processing
Nsmutablearray *mutableoperations = [Nsmutablearray array]; For (Nsurl *fileurl in filestoupload) { Nsurlrequest *request = [[Afhttprequestserializer serializer] multipartformrequestwithmethod:@ "POST" URLString:@ " Http://example.com/upload "Parameters:nil constructingbodywithblock:^ (id<afmultipartformdata> formData) { [FormData appendpartwithfileurl:fileurl name:@ "images[]" error:nil]; }]; Afhttprequestoperation *operation = [[Afhttprequestoperation alloc] initwithrequest:request]; [Mutableoperations addobject:operation]; } Nsarray *operations = [afurlconnectionoperation batchofrequestoperations:@[...] progressblock:^ (NSUInteger Numberoffinishedoperations, Nsuinteger totalnumberofoperations) { NSLog (@ "%lu of%lu Complete", numberoffinishedoperations, totalnumberofoperations); } completionblock:^ (Nsarray *operations) { NSLog (@ "All operations with batch complete"); }]; [[Nsoperationqueue Mainqueue] addoperations:operations Waituntilfinished:no]; |
The above API is based on NSURLCONNECTION,IOS7 and Afnetworking also provides a nsurlsession-based API
Nsurlsession-based API
Download task
Nsurlsessionconfiguration *configuration = [Nsurlsessionconfiguration defaultsessionconfiguration]; Afurlsessionmanager *manager = [[Afurlsessionmanager alloc] initwithsessionconfiguration:configuration]; Nsurl *url = [Nsurl urlwithstring:@ "Http://example.com/download.zip"]; Nsurlrequest *request = [Nsurlrequest Requestwithurl:url]; Nsurlsessiondownloadtask *downloadtask = [Manager downloadtaskwithrequest:request progress:nil Destination:^NSURL * ( Nsurl *targetpath, Nsurlresponse *response) { Nsurl *documentsdirectoryurl = [[Nsfilemanager Defaultmanager] urlfordirectory:nsdocumentdirectory inDomain: Nsuserdomainmask Appropriateforurl:nil Create:no Error:nil]; return [Documentsdirectoryurl Urlbyappendingpathcomponent:[response Suggestedfilename]]; } completionhandler:^ (Nsurlresponse *response, Nsurl *filepath, Nserror *error) { NSLog (@ "File downloaded to:%@", FilePath); }]; [Downloadtask resume]; |
File Upload Task
Nsurlsessionconfiguration *configuration = [Nsurlsessionconfiguration defaultsessionconfiguration]; Afurlsessionmanager *manager = [[Afurlsessionmanager alloc] initwithsessionconfiguration:configuration]; Nsurl *url = [Nsurl urlwithstring:@ "Http://example.com/upload"]; Nsurlrequest *request = [Nsurlrequest Requestwithurl:url]; Nsurl *filepath = [Nsurl fileurlwithpath:@ "File://path/to/image.png"]; Nsurlsessionuploadtask *uploadtask = [Manager uploadtaskwithrequest:request Fromfile:filepath Progress:nil completionhandler:^ (nsurlresponse *response, id responseobject, Nserror *error) { if (Error) { NSLog (@ "error:%@", error); } else { NSLog (@ "Success:%@%@", response, Responseobject); } }]; [Uploadtask resume]; |
File Upload with Progress
Nsmutableurlrequest *request = [[Afhttprequestserializer serializer] multipartformrequestwithmethod:@ "POST" urlstring:@ "Http://example.com/upload" Parameters:nil constructingbodywithblock:^ (id<afmultipartformdata> FormData) { [FormData appendpartwithfileurl:[nsurl fileurlwithpath:@ "file://path/to/image.jpg"] name:@ "file" filename:@ " Filename.jpg "mimetype:@" Image/jpeg "Error:nil"; } Error:nil]; Afurlsessionmanager *manager = [[Afurlsessionmanager alloc] Initwithsessionconfiguration:[nsurlsessionconfiguration Defaultsessionconfiguration]]; Nsprogress *progress = nil; Nsurlsessionuploadtask *uploadtask = [Manager uploadtaskwithstreamedrequest:request progress:&progress completionhandler:^ (nsurlresponse *response, id responseobject, Nserror *error) { if (Error) { NSLog (@ "error:%@", error); } else { NSLog (@ "%@%@", response, Responseobject); } }]; [Uploadtask resume]; Nsurlsessiondatatask Nsurlsessionconfiguration *configuration = [Nsurlsessionconfiguration defaultsessionconfiguration]; Afurlsessionmanager *manager = [[Afurlsessionmanager alloc] initwithsessionconfiguration:configuration]; Nsurl *url = [Nsurl urlwithstring:@ "Http://example.com/upload"]; Nsurlrequest *request = [Nsurlrequest Requestwithurl:url]; Nsurlsessiondatatask *datatask = [Manager datataskwithrequest:request completionhandler:^ (NSURLResponse *response, ID Responseobject, Nserror *error) { if (Error) { NSLog (@ "error:%@", error); } else { NSLog (@ "%@%@", response, Responseobject); } }]; [Datatask resume]; |
View network Status
Apple officially provides reachablity to view the status of the network, Afnetworking also provides this API
Nsurl *baseurl = [Nsurl urlwithstring:@ "http://example.com/"]; Afhttprequestoperationmanager *manager = [[Afhttprequestoperationmanager alloc] initwithbaseurl:baseurl]; Nsoperationqueue *operationqueue = Manager.operationqueue; [Manager.reachabilitymanager setreachabilitystatuschangeblock:^ (afnetworkreachabilitystatus status) { Switch (status) { Case Afnetworkreachabilitystatusreachableviawwan: Case Afnetworkreachabilitystatusreachableviawifi: [Operationqueue Setsuspended:no]; Break Case Afnetworkreachabilitystatusnotreachable: Default [Operationqueue Setsuspended:yes]; Break } }]; Start monitoring [Manager.reachabilitymanager startmonitoring]; |
Use of iOS network access afnetworking<2>