IOS Multithreading & Networking-4.0-AFN framework simple to use

Source: Internet
Author: User

A.AFN Basic Knowledge 1. Concept

    • Afnetworking
    • It's a package for nsurlconnection.
    • Operating efficiency without ASI high (because ASI is based on cfnetwork), but simple to use
    • AFN Support Arc

B. Basic request use 1. Basic use (1) header file AFNetworking.h (2) Manager class: Afhttprequestoperationmanager (3) "Get" method to send a GET request using "POST" Method sends a POST request (4) using a dictionary to send parameters (5) block processing request success/failure

 1/** Send get/post request */2-(void) Sendnormalrequest {3//1. Create Request Manager 4 Afhttprequestoperationmanager *manager = [Afhttprequestoperationmanager Manager]; 5 6//2. Set parameter 7 nsmutabledictionary *param = [Nsmutabledictionary dictionary]; 8 param[@ "user"] = @ "Tom"; 9 param[@ "password"] = @ "123"; 10 11//3. Send request////3.1 GET request//[manager get:@] Http://192.168.0.21:8 080/mytestserver/login "Parameters:param success:^ (afhttprequestoperation *operation, id responseObject) {+//NSL OG (@ "request succeeded"); NSLog (@ "%@", responseobject), +//} failure:^ (Afhttprequestoperation *operation, Nserror *err OR) {NSLog (@ "request Failed"), NSLog (@ "%@", error),//}];20//3.2 POST request [manager PO st:@ "Http://192.168.0.21:8080/MyTestServer/login" Parameters:param success:^ (afhttprequestoperation *operation, ID Responseobject) {NSLog (@ "request succeeded"), NSLog (@ "%@", Responseobject), failure:^ (afhttpreqUestoperation *operation, Nserror *error) {NSLog (@ "request Failed"), NSLog (@ "%@", error); 28}];29} 

  2. To facilitate viewing of the Chinese data returned by the server, add a category to the array and dictionary, support Chinese

 1 #import <Foundation/Foundation.h> 2 3 @implementation nsdictionary (LOG) 4 5/** Localized display */6-(NSString *) descr Iptionwithlocale: (ID) locale {7 nsmutablestring *str = [nsmutablestring string]; 8 9 [str appendstring:@ ' {\ n '] ; 10 11//Traversal dictionary [self enumeratekeysandobjectsusingblock:^ (ID key, id obj, BOOL *stop) {[str appendf ormat:@ "\t%@ =%@,\n", key, obj];14}];15 [str appendstring:@ "}"];17 18//Remove Last "," Nsrange RA Nge = [Str rangeofstring:@], "options:nsbackwardssearch];20 [str deletecharactersinrange:range];21-Return St r;23}24 @end26 @implementation Nsarray (Log)-(NSString *) Descriptionwithlocale: (id) locale {nsmutables Tring *str = [nsmutablestring string];31 [str appendstring:@ "[\ n]];33 34//traversal array all elements [self enumerat     eobjectsusingblock:^ (id obj, Nsuinteger idx, BOOL *stop) {[str appendformat:@ '%@, \ n ', obj];37}];38 39 [Str appendstring:@]] "];40 return str;42}43 @end 

3. Parse the returned JSON data

    • Afhttprequestoperationmanager relies on the setup serializer to automatically identify and parse the returned data
    • JSON parsing is used by default, so you don't have to set the serializer
    • will automatically convert the JSON into a dictionary or an array output.
 1/** returns JSON data */2-(void) Getjson {3//1. Create Request Manager 4 Afhttprequestoperationmanager *manager = [afhttpreq Uestoperationmanager Manager]; 5 6//Set serializer 7//[Manager Setresponseserializer:[afjsonresponseserializer serializer]];//Default 8 9//2. Settings Parameters nsmutabledictionary *param = [nsmutabledictionary dictionary];11 param[@ "type"] = @ "JSON"; 12 13//3. Hair Send Request [manager get:@ "Http://192.168.0.21:8080/MyTestServer/video" Parameters:param success:^ ( Afhttprequestoperation *operation, id responseobject) {NSLog (@ "request succeeded"), + NSLog (@ "The data type returned is:%@", [respons Eobject class]), NSLog (@ "%@", Responseobject), failure:^ (afhttprequestoperation *operation, Nserror *err OR) {NSLog (@ "request Failed"), NSLog (@ "%@", error),}];22} 

  output:  2015-01-30 03:34:14.817 afnbasicdemo[1889:192783]   Request succeeded
2015-01-30 03:34:14.817 afnbasicdemo[1889:192783]
  The returned data type is : __nscfdictionary
2015-01-30 03:34:14.818 afnbasicdemo[1889:192783] {
Videos = [
{
name =
  Dragon trainer 1,
video = videos/1.mp4,
length = +
seconds ,
image = images/[20150124-180852-0]. PNG
  },   ...      4. Parsing the returned XML data settings use an XML serializer, or you can automatically convert the XML data into a dictionary or an array if the XML serializer is not set, processing the returned data fails  

 1/** returns XML data */2-(void) getxml{3//1. Create Request Manager 4 Afhttprequestoperationmanager *manager = [afhttpreques Toperationmanager Manager]; 5 6//Set Serializer 7 [manager Setresponseserializer:[afxmlparserresponseserializer Serializer]]; 8 9//2. Set parameters nsmutabledictionary *param = [nsmutabledictionary dictionary];11 param[@ "type"] = @ "xml"; 1 2 13 14//3. Send Request __weak typeof (self) VC = self;16 [Manager get:@ "Http://192.168.0.21:8080/MyTestServe         R/video "Parameters:param success:^ (afhttprequestoperation *operation, id responseobject) {NSLog (@" request succeeded "); 18 NSLog (@ "returned data type is:%@", [Responseobject class]); Nsxmlparser *parser = (Nsxmlparser *) responseobj ect;21 parser.delegate = vc;22 [Parser parse];23} failure:^ (Afhttprequestoperation *operation, NSErro R *error) {NSLog (@ "request Failed"), NSLog (@ "%@", error);}];27} 

C. File download/upload 1. File download

    • is also a simple send request
    • But there's no such thing as ASI's listening capabilities

 1-(void) DownloadFile {2//1. Create Request Manager 3 Afhttprequestoperationmanager *manager = [afhttprequestoperationmanage R Manager]; 4 5//Set serializer 6 [manager Setresponseserializer:[afhttpresponseserializer Serializer]]; Using binary Data Serialization 7 8//3. Send Request 9 [manager get:@ "Http://192.168.0.21:8080/MyTestServer/images/images.zip" Paramete Rs:nil success:^ (afhttprequestoperation *operation, id responseobject) {ten NSLog (@ "request succeeded"); NSL OG (@ "Returned data type is:%@", [Responseobject class]); NSString *cachepath = [nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) lastobject];15 nsstring *filepath = [CachePath stringbyappendingpathcom ponent:@ "Download.zip"];16 nsdata *data = (NSData *) responseobject;17 [data Writetofile:filepath atomical         LY:YES];18} failure:^ (Afhttprequestoperation *operation, Nserror *error) {NSLog (@ "request Failed"); 21 NSLog (@ "%@", error); 22}];25; 

2. File Upload

    • Post method with Formdata with POST request
    • To distinguish between common parameters and file parameters, it is not possible to upload file data in normal parameters.
    • The file is assigned in the block parameter

(1) Converting files into binary data (2) stitching file parameters

 1/** Upload file */2-(void) UploadFile {3//1. Create Request Manager 4 Afhttprequestoperationmanager *manager = [Afhttprequestope Rationmanager Manager]; 5 6//2. Set parameter 7 nsmutabledictionary *param = [Nsmutabledictionary dictionary]; 8 param[@ "user"] = @ "uploader"; 9 10//3. Set upload file one by one nsstring *filepath = [[NSBundle mainbundle] pathforresource:@ "m2.jpg" oftype:nil];12 NSD  ATA *filedata = [NSData datawithcontentsoffile:filepath];13 14//4. Uploading Files: __weak typeof (FileData) Uploaddata = filedata;16 [manager post:@ "Http://192.168.0.21:8080/MyTestServer/upload" Parameters:param Constructingbodywith block:^ (id<afmultipartformdata> formData) {18 19//splicing file data [FormData Appendpartwithfiledata : Uploaddata name:@ "UploadedFile" filename:@ "my_pic.jpg" mimetype:@ "Image/jpg"];21 (success:^) AFHTTPRequestO Peration *operation, id responseobject) {NSLog (@ "Upload succeeded----%@", responseobject); failure:^ (AFHTTPREquestoperation *operation, Nserror *error) {NSLog (@ "Upload failed----%@", error); 26}];27} 

  &NBSP;&NBSP; D. Network status monitoring  afnetworkreachabilitymanager (1) Creating a Network Monitoring Manager (2) Setting up monitoring network status changes (3) Open monitoring (4) can also take the initiative to obtain network status  

 1-(Ibaction) Monitornetwork: (UIButton *) Sender {2//1. Create Network Status Monitoring Manager 3 Afnetworkreachabilitymanager *manager = [A Fnetworkreachabilitymanager Sharedmanager];         4 5//2. Network Status Change event (passive detection) 6 [Manager setreachabilitystatuschangeblock:^ (Afnetworkreachabilitystatus status) {7                 Switch (status) {8 case Afnetworkreachabilitystatusunknown:9 NSLog (@ "converted to unknown network"); 10 break;11 Case Afnetworkreachabilitystatusreachableviawwan:12 NSLog (@ "Convert to mobile Network"); 1 3 break;14 Case afnetworkreachabilitystatusreachableviawifi:15 NSLog (@ "Convert to WiFi Network "), Break;17 case afnetworkreachabilitystatusnotreachable:18 NSLog (@" converted to No    Network "), break;20 default:22 break;23}24}];25 26//Open Monitor [manager startmonitoring];28 29//Active detection ([manager isreachable]) {NSLog (@ "now has the network"), the "Else if" ([manager Isreachableviawifi]) {NSLog (@ "now over WiFi"); Se if ([manager Isreachableviawwan]) {NSLog (@ "Now on mobile internet"), +-else {PNS NSLog (@ "No network Now"); 38} 39}

[IOS Multithreading & Networking-4.0]-AFN framework simple to use

IOS Multithreading & Networking-4.0-AFN framework simple to 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.