AFN Framework Basic Use

Source: Internet
Author: User

+ 8.1AFN Internal Structure
AFN Structural Body
-Nsurlconnection
+ afurlconnectionoperation
+ afhttprequestoperation
+ Afhttprequestoperationmanager (Encapsulation of common HTTP methods)
* Properties
* BASEURL:AFN recommends that developers customize a single example class for Afhttprequestoperationmanager, set BaseURL, and all network access, using only relative paths
* Requestserializer: Request data Format/default is binary HTTP
* Responseserializer: Response data Format/default is JSON format
* Operationqueue
* Reachabilitymanager: Network Connection Manager
* Method
* Manager: Easy class method for creating manager
* Httprequestoperationwithrequest: When accessing the server, if you want to tell the server some additional information, you need to set in Request
* GET
* POST

-Nsurlsession
+ Afurlsessionmanager
+ Afhttpsessionmanager (Encapsulation of common HTTP methods)
* GET
* POST
* UIKit + afnetworking Category
* Nsprogress: Using KVO

-Semi-automatic serialization & deserialization functions
+ Afurlrequestserialization: The requested data format/default is binary
+ afurlresponseserialization: Data format for response/default is JSON format
-Additional functions
+ Security Policy
* HTTPS
* Afsecuritypolicy
+ Network Detection
* A package for Apple's network connection detection
* Afnetworkreachabilitymanager

-Basic use of 8.2 AFN

(1) Two ways to send a GET request (post same)
-(void) get1{//1. Create a Afhttprequestoperationmanager manager//Afhttprequestoperationmanager Internal is based on the nsurlconnection implementationAfhttprequestoperationmanager *manager =[Afhttprequestoperationmanager Manager]; //2. Sending the request    /*     http://120.25.226.186: 32812/login?username=ee&pwd=ee&type=json The first parameter: the request path of the NSString type, which automatically wraps the path as a URL and creates the request object inside the AFN     The second parameter: request parameters, passed in a dictionary, AFN internally will determine whether the current post request or GET request, to choose a direct stitching or conversion to nsdata into the request body to pass the third parameter: After the request succeeds callback block fourth parameter: Request failed callback block */nsdictionary*param = @{                            @"username":@"520it",                            @"pwd":@"520it"                            }; //Note: The string cannot contain spaces[Manager GET:@"Http://120.25.226.186:32812/login"Parameters:param success:^ (afhttprequestoperation * _nonnull operation,ID_nonnull Responseobject) {NSLog (@"Successful Request---%@", Responseobject); } Failure:^ (Afhttprequestoperation * _nonnull operation, Nserror *_nonnull Error) {NSLog (@"Failure---%@", error); }];}-(void) get2{//1. Create a Afhttpsessionmanager manager//Afhttpsessionmanager Internal is based on the nsurlsession implementationAfhttpsessionmanager *manager =[Afhttpsessionmanager Manager]; //2. Sending the requestNsdictionary *param = @{                            @"username":@"520it",                            @"pwd":@"520it"                            }; //Note: responseobject: The response result of the request successfully returned (AFN has converted the response body to an OC object, usually a dictionary or an array)[Manager GET:@"Http://120.25.226.186:32812/login"Parameters:param success:^ (Nsurlsessiondatatask * _nonnull task,ID_nonnull Responseobject) {NSLog (@"Successful Request---%@", [Responseobjectclass]); } Failure:^ (Nsurlsessiondatatask * _nonnull task, Nserror *_nonnull Error) {NSLog (@"Failure---%@", error); }];}

(2) Download files using AFN
-(void) download{//1. Create a managerAfhttpsessionmanager *manage =[Afhttpsessionmanager Manager]; //2. Download the file    /*first parameter: Request object second parameter: Download progress third parameter: Block callback, need to return a URL address, used to tell AFN the destination address of the download file Targetpath:afn the address of the internal download file storage, tmp folder Next response: Request response header return value: where the file should be clipped fourth parameter: Block callback, when the file download is complete, call Response: Response header filePath: file stored in the sand Box Address = = The return value of block in the third parameter error: Wrong message*/    //2.1 Creating a Request objectNsurlrequest *request = [Nsurlrequest requestwithurl:[nsurl urlwithstring:@"Http://120.25.226.186:32812/resources/images/minion_02.png"]]; //2.2 Create the download progress and listenNsprogress *progress =Nil; Nsurlsessiondownloadtask*downloadtask = [Manage Downloadtaskwithrequest:request progress:&progress Destination:^nsurl * _Nonnull (NSURL * _ Nonnull TargetPath, Nsurlresponse *_nonnull Response) {NSString*caches =[Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) lastobject]; //stitching file Full pathNSString *fullpath =[Caches stringByAppendingPathComponent:response.suggestedFilename]; Nsurl*filepathurl =[Nsurl Fileurlwithpath:fullpath]; returnFilepathurl; } Completionhandler:^ (Nsurlresponse * _nonnull response, Nsurl * _nonnull FilePath, Nserror *_nonnull Error) {NSLog (@"File Download Complete---%@", FilePath);    }]; //2.3 using KVO to monitor download progress[Progress Addobserver:self Forkeypath:@"Completedunitcount"Options:nskeyvalueobservingoptionnew Context:nil]; //3. Start a task[Downloadtask resume];}//gets and calculates the download progress of the current file-(void) Observevalueforkeypath: (NSString *) keypath ofobject: (nsprogress *) Progress change: (Nsdictionary<nsstring *,ID> *) Change context: (void*) context{NSLog (@"%zd--%zd--%f", Progress.completedunitcount,progress.totalunitcount,1.0* progress.completedunitcount/progress.totalunitcount);}

AFN Framework Basic Use

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.