Get ready
first, you need to include the afnetworking framework in the project. If you haven't afnetworking, download the latest version here:
Https://github.com/AFNetworking/AFNetworking
When you extract the downloaded files, you will see that there is a afnetworking subfolder with the. h and. m files, which are highlighted below:
Drag the afnetworking to the Xcode project.
When the option to add a file appears, make sure that the copy items into destination group ' s folder (if needed) and the Create groups for any added folders are checked.
Adding afnetworking to the precompiled header file means that the framework is automatically added to all of the project's source code files.
Introduction to Common methods
Method One: Get request
Copy Code code as follows:
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);
}];
method Two: POST request
Copy Code code as follows:
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);
}];
Method III: POST multi-part Request
Copy Code code as follows:
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);
}];
method Four: Create a download file task
Copy Code code as follows:
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];
method Five: Create an upload file task
Copy Code code as follows:
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];
method Six: Create an upload file task and show progress
Copy Code code as follows:
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];
method Seven: Create an upload data task
Copy Code code as follows:
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];
method Eight: Get network status
Copy Code code as follows:
[[Afnetworkreachabilitymanager Sharedmanager] setreachabilitystatuschangeblock:^ (AFNetworkReachabilityStatus Status) {
NSLog (@ "reachability:%@", Afstringfromnetworkreachabilitystatus (status));
}];
Method IX: HTTP Manager reachability
Copy Code code as follows:
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;
}
}];
[Manager.reachabilitymanager startmonitoring];
method Ten: Afhttprequestoperation GET request
Copy Code code as follows:
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];
Method 11: Batch of Operations
Copy Code code as follows:
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 complete");
}];
[[Nsoperationqueue Mainqueue] addoperations:operations Waituntilfinished:no];
Method 12: Get some information about the request (I have not used it, not very often)
Copy Code code as follows:
Request serialization
Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body.
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": [1,2,3]}