iOS Development--afnetworking Framework use detailed

Source: Internet
Author: User

Afnetworking is a delightful networking library for IOS and Mac OS x.it ' s built on top of the Foundation URL Loading syste M, extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, and Feature-rich APIs that is a joy to use.

Afnetworking is a popular network class library based on iOS and Mac OS x. Built on top of the framework of the URL loading system, it builds on the cocoa, extending a powerful high-level network abstraction. It is enjoyable to have a well-designed modular architecture and rich functionality.

Download Link: https://github.com/AFNetworking/AFNetworking

How to use:
1.GET Request

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];[manager GET:@"http://example.com/resources.json" parameters:nilid responseObject) {    NSLog(@"JSON: %@"NSError *error) {    NSLog(@"Error: %@", error);}];

2.POST Request

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];NSDictionary *parameters = @{@"foo": @"bar"};[manager POST:@"http://example.com/resources.json"id responseObject) {    NSLog(@"JSON: %@"NSError *error) {    NSLog(@"Error: %@", error);}];

3.POST multi-part Request

Afhttprequestoperationmanager *manager = [Afhttprequestoperationmanager manager];nsdictionary*parameters = @{@"foo": @"Bar"};Nsurl*filepath = [Nsurlfileurlwithpath:@"File://path/to/image.png"]; [Manager post:@"Http://example.com/resources.json"Parameters:parameters constructingbodywithblock:^ (ID<AFMultipartFormData> formData) {[FormData Appendpartwithfileurl:filepath name:@"Image"ErrorNil];} success:^ (Afhttprequestoperation *operation,IDResponseobject) {NSLog(@"Success:%@", responseobject);} failure:^ (Afhttprequestoperation *operation,Nserror*error) {NSLog(@"Error:%@", error);}];

4. Create a download task

Nsurlsessionconfiguration *configuration = [Nsurlsessionconfiguration defaultsessionconfiguration]; Afurlsessionmanager *manager = [[Afurlsessionmanager alloc] initwithsessionconfiguration:configuration];Nsurl*url = [Nsurlurlwithstring:@"Http://example.com/download.zip"];nsurlrequest*request = [nsurlrequestRequestwithurl:url]; Nsurlsessiondownloadtask *downloadtask = [Manager downloadtaskwithrequest:request Progress:Nildestination:^Nsurl*(Nsurl*targetpath, Nsurlresponse *response) {Nsurl*documentsdirectoryurl = [[NsfilemanagerDefaultmanager] Urlfordirectory:nsdocumentdirectory indomain:nsuserdomainmask appropriateforurl:NilCreateNOErrorNil];return[Documentsdirectoryurl urlbyappendingpathcomponent:[response suggestedfilename];} completionhandler:^ (Nsurlresponse *response,Nsurl*filepath,Nserror*error) {NSLog(@"File downloaded to:%@", FilePath);}]; [Downloadtask resume];

5. Create an upload task

Nsurlsessionconfiguration *configuration = [Nsurlsessionconfiguration defaultsessionconfiguration]; Afurlsessionmanager *manager = [[Afurlsessionmanager alloc] initwithsessionconfiguration:configuration];Nsurl*url = [Nsurlurlwithstring:@"Http://example.com/upload"];nsurlrequest*request = [nsurlrequestRequestwithurl:url];Nsurl*filepath = [Nsurlfileurlwithpath:@"File://path/to/image.png"]; Nsurlsessionuploadtask *uploadtask = [Manager uploadtaskwithrequest:request Fromfile:filepath Progress:Nilcompletionhandler:^ (Nsurlresponse *response,IDResponseobject,Nserror*error) {if(Error) {NSLog(@"Error:%@", error); }Else{NSLog(@"Success:%@%@", response, Responseobject); }}]; [Uploadtask resume];

6. Create an upload file task and show progress

Nsmutableurlrequest *request = [[Afhttprequestserializer serializer] multipartformrequestwithmethod:@"POST"urlstring:@"Http://example.com/upload"ParametersNilconstructingbodywithblock:^ (ID<AFMultipartFormData> formData) {[FormData appendpartwithfileurl:[Nsurlfileurlwithpath:@"File://path/to/image.jpg"] name:@"File"filename:@"Filename.jpg"mimetype:@"Image/jpeg"ErrorNil]; } Error:Nil]; Afurlsessionmanager *manager = [[Afurlsessionmanager alloc] Initwithsessionconfiguration:[nsurlsessionconfiguration Defaultsessionconfiguration]]; Nsprogress *progress =Nil; Nsurlsessionuploadtask *uploadtask = [Manager uploadtaskwithstreamedrequest:request progress:&progress completionhandler:^ (Nsurlresponse *response,IDResponseobject,Nserror*error) {if(Error) {NSLog(@"Error:%@", error); }Else{NSLog(@"%@ %@", response, Responseobject); }}]; [Uploadtask resume];

7. Create a Data Flow task

Nsurlsessionconfiguration *configuration = [Nsurlsessionconfiguration defaultsessionconfiguration]; Afurlsessionmanager *manager = [[Afurlsessionmanager alloc] initwithsessionconfiguration:configuration];Nsurl*url = [Nsurlurlwithstring:@"Http://example.com/upload"];nsurlrequest*request = [nsurlrequestRequestwithurl:url]; Nsurlsessiondatatask *datatask = [Manager datataskwithrequest:request completionhandler:^ (NSURLResponse *response,IDResponseobject,Nserror*error) {if(Error) {NSLog(@"Error:%@", error); }Else{NSLog(@"%@ %@", response, Responseobject); }}]; [Datatask resume];

8. Get Network status

[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));}];[[AFNetworkReachabilityManager sharedManager] startMonitoring];

9.HTTP Manager reachability (Accessibility)

Nsurl*baseurl = [Nsurlurlwithstring:@"http://example.com/"]; Afhttprequestoperationmanager *manager = [[Afhttprequestoperationmanager alloc] initwithbaseurl:baseurl]; Nsoperationqueue *operationqueue = Manager. Operationqueue; [Manager. Reachabilitymanagersetreachabilitystatuschangeblock:^ (afnetworkreachabilitystatus status) {Switch(status) { CaseAfnetworkreachabilitystatusreachableviawwan: CaseAfnetworkreachabilitystatusreachableviawifi: [Operationqueue setsuspended:NO]; Break; CaseAfnetworkreachabilitystatusnotreachable:default: [Operationqueue setsuspended:YES]; Break; }}]; [Manager. ReachabilitymanagerStartmonitoring];

10.AFHTTPRequestOperation GET Request (Afhttprequestoperationmanager is usually the best way to go, but afhttprequestopersion can also be used alone)

Nsurl*url = [Nsurlurlwithstring:@"Http://example.com/resources/123.json"];nsurlrequest*request = [nsurlrequestRequestwithurl:url]; Afhttprequestoperation *op = [[Afhttprequestoperation alloc] Initwithrequest:request];op. Responseserializer= [Afjsonresponseserializer serializer]; [Op setcompletionblockwithsuccess:^ (Afhttprequestoperation *operation,IDResponseobject) {NSLog(@"JSON:%@", responseobject);} failure:^ (Afhttprequestoperation *operation,Nserror*error) {NSLog(@"Error:%@", error);}]; [[Nsoperationqueue Mainqueue] addoperation:op];

11.Batch of Operations

Nsmutablearray*mutableoperations = [NsmutablearrayArray]; for(Nsurl*fileurl in Filestoupload) {nsurlrequest*request = [[Afhttprequestserializer serializer] multipartformrequestwithmethod:@"POST"urlstring:@"Http://example.com/upload"ParametersNilconstructingbodywithblock:^ (ID<AFMultipartFormData> formData) {[FormData appendpartwithfileurl:fileurl name:@"images[]"ErrorNil];    }];    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 complete");}]; [[Nsoperationqueue Mainqueue] addoperations:operations waituntilfinished:NO];

The above is some common methods in afnetworking, afnetworking request to the data, automatically parse the requested data, iOS data request This aspect afnetworking is a very good third-party library.

iOS Development--afnetworking Framework use detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.