iOS network access using Afnetworking afnetworking is a popular third-party network access Library on iOS, and we can download it on GitHub, with detailed instructions for use on GitHub, The latest AFNetworing2.0 and 1.0 have changed a lot, and this is only a summary of the 2.0 common usage methods based on the Nsurlconnection APIsubmit a GET requestAfhttprequestoperationmanager *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); }];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)
Manager.responseserializer = [Afhttpresponseserializer serializer]; This sentence can also, very important, remove it is easy to encounter errors, temporarily did not understand the more detailed reasons
If we return the plist format, we use the Afpropertylistresponseserializer parser, and if we return an XML format, we'll use the Afxmlparserresponseserializer parser. Responseobject represents the Nsxmlparser to the image if the return is a picture, you can use the Afimageresponseserializer if you just want to get the binary format returned, You can also use the Afhttpresponseserializer Afrequestserializer Afhttprequestoperationmanager to set the requested format by setting the Requestseializer propertylike the following request address and parametersNSString *urlstring = @ "http://example.com"; Nsdictionary *parameters = @{@ "foo": @ "bar" @ "baz": @[@1, @2, @3]}; We use Afhttprequestserializer's get submission method [[Afhttprequestserializer Serializer] requestwithmethod:@ "Get" URLString: URLString parameters:parameters Error:nil]; GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3 We use Afhttprequestserializer's 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-one]} The data for the default commit request is binary (afhttprequestseri Alizer), 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 inherit from Afurlconnectionoperation, afurlconnectionoperation inherit from Nsoperation, Therefore, a network request task can be defined through afhttprequestoperation and then added to the queue for execution.
| Nsmutablearray *mutableoperations = [Nsmutablearray array];for (Nsurl *fileurl in filestoupload) {NSUR Lrequest *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 in Batch");}]; [[Nsoperationqueue Mainqueue] addoperations:operations Waituntilfinished:no]; |
Bulk task Processing
| Nsmutablearray *mutableoperations = [Nsmutablearray array];for (Nsurl *fileurl in filestoupload) {NSUR Lrequest *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 in Batch");}]; [[Nsoperationqueue Mainqueue] addoperations:operations Waituntilfinished:no]; |
The above API is based on NSURLCONNECTION,IOS7 and Afnetworking also provides a nsurlsession-based APINsurlsession-based APIDownload 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]; Nsurlsessiondatatasknsurlsessionconfiguration *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 StatusApple 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