Afnetworking Technology Reserve for the Korean Rim project

Source: Internet
Author: User

HTTP Request Operation Manager
Afhttprequestoperationmanager encapsulates Factory mode, communicating with Web server over HTTP, including creating requests, responding to serialization, network status 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 url-Form-Encoding 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 multi-part 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);
}];

Afurlsessionmanager
Afurlsessionmanager creates and manages a Nsurlsession object, based on the specified Nsurlsessionconfiguration object, in accordance with < Nsurlsessiontaskdelegate >, < Nsurlsessiondatadelegate > < nsurlsessiondownloaddelegate >,< nsurlsessiondelegate >.
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 a multipart Request upload task, 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];

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

Request serialization
Requests the serializer to create the URL string parameter, query string, or HTTP content of the encoding request.
NSString *urlstring = @ "http://example.com";
Nsdictionary *parameters = @{@ "foo": @ "bar" @ "baz": @[@1, @2, @3]};
Query string parameter encoding
[[Afhttprequestserializer Serializer] requestwithmethod:@ "GET" urlstring:urlstring parameters:parameters Error:nil] ;

GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3


URL Form parameter encoding
[[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

JSON parameter encoding
[[Afjsonrequestserializer Serializer] requestwithmethod:@ "POST" urlstring:urlstring parameters:parameters];


POST http://example.com/
Content-type:application/json

{"foo": "Bar", "baz": [All-in-all]}


Network state Management

Afnetworkreachabilitymanager Monitoring network status

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

HTTP Manager reachability
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
}
}];


Security Policy
Afsecuritypolicy evaluates server trust against pinned, certificates and public keys over secure connections.
Adding pinned SSL certificates to your apps helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information is strongly encouraged to route all Communicat Ion over a HTTPS connection with SSL pinning configured and enabled.

Allow an invalid SSL certificate
Afhttprequestoperationmanager *manager = [Afhttprequestoperationmanager manager];
Manager.securityPolicy.allowInvalidCertificates = YES; Not recommended for production


Afhttprequestoperation
Afhttprequestoperation Afurlconnectionoperation Subclass requests Use the HTTP or HTTPS protocol. It encapsulates the concept and content type of an acceptable status code to determine the success or failure of a request.
Although Afhttprequestoperationmanager is usually the best way to make a request, you can use the afhttprequestoperation itself.

Get request with afhttprequestoperation
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];

Batch processing operations
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 in batch");
}];
[[Nsoperationqueue Mainqueue] addoperations:operations Waituntilfinished:no];

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.