iOS network Programming (7) third-party open Source Library----->afnetworking

Source: Internet
Author: User

Afnetworking is a delightful network library made for IOS and Mac OSX , built on a URL The top layer of the loading system framework, built into the cocoa, expands the powerful advanced network abstraction. Its modular architecture is well designed and has a rich range of functions, so it is certainly pleasing to use.

@ original link https://github.com/AFNetworking/AFNetworking, I based on the point configuration modification

@ Introduction

1. Support for HTTP requests and rest-based network services (including GET, POST, PUT, delete, etc.)
2. Support Arc
3. Requires iOS 5.0 and later

4.UIKit expansion


@ configuration

1. Download the afnetworking and drag 2 folders: afnetworking and uikit+afnetworking into the project

2. Import the following library files: cfnetwork, Security, SystemConfiguration, mobilecoreservices

3. If you have previously used version 1.0, then Afnetworking 2.0 Migration Guide can help you

4. If you are configuring with Cocoapods, then

Platform:ios, ' 7.0 '

Pod "afnetworking", "~>2.0"


@ Use

1.HTTP Request operation

The common pattern of Afhttprequestoperationmanager encapsulation communicates with Web applications over HTTP, including creation of requests, response serialization, network accessibility monitoring, operational management and security, and requests.

*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);}];

*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);}];
*post requests (multiple tables)

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);}];
             

2.Afurlsessionmanager (nsurlsession See network Programming in detail (6))

Create and manage established Nsurlsession objects Nsurlsessionconfiguration object must implement <nsurlsessiontaskdelegate>, <nsurlsessiondatadelegate>, < Nsurlsessiondownloaddelegate>, <NSURLSessionDelegate> Agreement

* Create a 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];
* Create an 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];
* Create an upload task with multiple tables and progress

nsmutableurlrequest *request = [[Afhttprequestserializer serializer] multipartformrequestwithmethod:@ "POST" urlstring:@ "Http://example.com/upload" Parameters:nil constructingbodywithblock:^ (id<afmultipartformdata> formData) {[FormData appendpartwithfileurl:[nsurl FileUR    lwithpath:@ "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]; 
* Create a Dataflow data task

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 (@ "%@%@", Respo NSE, Responseobject);}    }]; [Datatask resume];

3. Network monitoring (usually with another network monitoring class, reachability, and JSON parsing method, anyway I also generally do not, self-brain repair)

The Afnetworkreachabilitymanager monitors the accessibility of the network domain, the Wwan address and the WiFi interface.

* Current network status

[[Afnetworkreachabilitymanager Sharedmanager] setreachabilitystatuschangeblock:^ (AFNetworkReachabilityStatus Status) {    NSLog (@ "reachability:%@", Afstringfromnetworkreachabilitystatus (status));}];

*http Manager Accessibility

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;    }}];

4.AFHTTPRequestOperation

Afhttprequestoperation is a subclass of Afurlconnectionoperation that uses the HTTP or HTTPS protocol.
The acquired HTTP state and type of the package it encapsulates will determine the success or not of the request. Although Afhttprequestoperationmanager is usually the best way to request it, afhttprequestopersion can also be used alone.
*GET request

Nsurl *url = [Nsurl urlwithstring:@ "Http://example.com/resources/123.json"]; Nsurlrequest *request = [Nsurlrequest Requestwithurl:url]; Afhttprequestoperation *op = [[Afhttprequestoperation alloc] Initwithrequest:request];op.responseserializer = [ Afjsonresponseserializer Serializer]; [Op setcompletionblockwithsuccess:^ (afhttprequestoperation *operation, id responseobject) {    NSLog (@ "JSON:%@", responseobject);} failure:^ (afhttprequestoperation *operation, Nserror *error) {    NSLog (@ "error:%@", error);}]; [[Nsoperationqueue Mainqueue] addoperation:op];

* Bulk Multi-Request

Nsmutablearray *mutableoperations = [Nsmutablearray array];for (Nsurl *fileurl in filestoupload) {NSURLRequest *reques t = [[Afhttprequestserializer serializer] multipartformrequestwithmethod:@ "POST" urlstring:@ "http://example.com/ Upload "Parameters:nil constructingbodywithblock:^ (id<afmultipartformdata> formData) {[FormData Appendpartwi    Thfileurl: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", Numberoffinishedoperat ions, totalnumberofoperations);} completionblock:^ (Nsarray *operations) {NSLog (@ "All operations in Batch");}]; [[Nsoperationqueue Mainqueue] addoperations:operations Waituntilfinished:no];

@ Other Information

1. official website

2. English documents









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.