AFNetworking2.5 use

Source: Internet
Author: User

1. Detecting Network status

+ (void) NetworkStatus {/** Afnetworkreachabilitystatusunknown =-1,//unknown afnetworkreachabilitystatusnotreachable = 0,//no connection Afnetworkreachabilitystatusreachableviawwan = 1,//3G cost Afnetworkreachabilitystatus Reachableviawifi = 2,//WiFi*/          //if you want to detect changes in network status, you must use the startmonitoring of the Test manager's Singleton[[Afnetworkreachabilitymanager Sharedmanager] startmonitoring]; //A single case for detecting network connections and a callback method for network changes[[Afnetworkreachabilitymanager Sharedmanager] setreachabilitystatuschangeblock:^(afnetworkreachabilitystatus status) {NSLog (@"%ld", status);      }]; }  

2.JSON Way to get data

+ (void) Jsondatawithurl: (NSString *) URL success: (void(^) (IDJSON) Success fail: (void(^) ()) fail; {Afhttprequestoperationmanager*manager =[Afhttprequestoperationmanager Manager]; Nsdictionary*dict = @{@"format":@"JSON"}; //Network access is asynchronous, callbacks are the main thread, so programmers don't have to do things that update the UI on the main thread[Manager Get:url Parameters:dict success:^ (afhttprequestoperation *operation,IDresponseobject) {              if(Success) {success (responseobject); }} failure:^ (Afhttprequestoperation *operation, Nserror *error) {NSLog (@"%@", error); if(fail) {fail ();      }          }]; }  

3.xml Way to get data

+ (void) Xmldatawithurl: (NSString *) Urlstr success: (void(^) (IDXML) Success fail: (void(^) ()) fail {Afhttprequestoperationmanager*manager =[Afhttprequestoperationmanager Manager]; //The returned data format is XMLManager.responseserializer =[Afxmlparserresponseserializer Serializer]; Nsdictionary*dict = @{@"format":@"XML"}; //Network access is asynchronous, callbacks are the main thread, so programmers don't have to do things that update the UI on the main thread[Manager get:urlstr Parameters:dict success:^ (afhttprequestoperation *operation,IDresponseobject) {              if(Success) {success (responseobject); }} failure:^ (Afhttprequestoperation *operation, Nserror *error) {NSLog (@"%@", error); if(fail) {fail ();      }          }]; }  

4.post Submitting JSON data

+ (void) Postjsonwithurl: (NSString *) urlstr parameters: (ID) Parameters Success: (void(^) (IDResponseobject)) Success fail: (void(^) ()) fail {Afhttprequestoperationmanager*manager =[Afhttprequestoperationmanager Manager]; //Set Request FormatManager.requestserializer =[Afjsonrequestserializer Serializer]; //Set return formatManager.responseserializer =[Afhttpresponseserializer Serializer]; [Manager post:urlstr parameters:parameters success:^ (Afhttprequestoperation *operation,IDresponseobject) {      //nsstring *result = [[NSString alloc] Initwithdata:responseobject encoding:nsutf8stringencoding];             if(Success) {success (responseobject); }} failure:^ (Afhttprequestoperation *operation, Nserror *error) {NSLog (@"%@", error); if(fail) {fail ();                }          }]; }  

5. Download the file

+ (void) Sessiondownloadwithurl: (NSString *) Urlstr success: (void(^) (Nsurl *fileurl)) Success Fail: (void(^) ()) fail {nsurlsessionconfiguration*config =[Nsurlsessionconfiguration defaultsessionconfiguration]; Afurlsessionmanager*manager =[[Afurlsessionmanager alloc] initwithsessionconfiguration:config]; NSString*urlstring =[Urlstr stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]; Nsurl*url =[Nsurl urlwithstring:urlstring]; Nsurlrequest*request =[Nsurlrequest Requestwithurl:url]; Nsurlsessiondownloadtask*task = [Manager downloadtaskwithrequest:request progress:nil Destination:^nsurl * (Nsurl *targetpath, NSURLResponse *response) {              //specify the path to save the download file//NSLog (@ "%@%@", TargetPath, Response.suggestedfilename); //Save the download file in the cache pathNSString *cachedir = Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) [0]; NSString*path =[Cachedir StringByAppendingPathComponent:response.suggestedFilename]; //urlwithstring Returns the URL of the network, if you use a local URL, you need to be aware//Nsurl *FILEURL1 = [Nsurl Urlwithstring:path]; Nsurl *fileurl =[Nsurl Fileurlwithpath:path]; //NSLog (@ "= =%@ | | | |%@", fileURL1, FileURL);             if(Success) {success (FileURL); }                            returnFileURL; } Completionhandler:^ (Nsurlresponse *response, Nsurl *filepath, Nserror *error) {NSLog (@"%@ %@", FilePath, error); if(fail) {fail ();                    }          }];      [Task resume]; }  

6. File upload-Custom upload file name

+ (void) Postuploadwithurl: (NSString *) urlstr FILEURL: (nsurl *) FILEURL filename: (nsstring *) filename fileType: (NSString *) Filetye Success: (void(^) (IDResponseobject)) Success fail: (void(^) ()) fail{//local to the server, there is no definite URL, bad MD5 way to handleAfhttprequestoperationmanager *manager =[Afhttprequestoperationmanager Manager]; Manager.responseserializer=[Afhttpresponseserializer Serializer]; //@"http://localhost/demo/upload.php"[Manager post:urlstr Parameters:nil constructingbodywithblock:^ (ID<AFMultipartFormData>formData) {        //Nsurl *fileurl = [[NSBundle mainbundle] urlforresource:@ "Avatar 1.png" withextension:nil]; //to upload a name saved in the server//use time as filename 2014-04-30 14:20:57.png//allow different user information to be saved in different directories//NSDateFormatter *formatter = [[NSDateFormatter alloc] init];//        //Set Date format//Formatter.dateformat = @ "Yyyy-mm-dd HH:mm:ss";//nsstring *filename = [formatter stringfromdate:[nsdate date]]; //@ "Image/png"[FormData appendpartwithfileurl:fileurl Name:@"UploadFile"filename:filename Mimetype:filetye Error:null]; } Success:^ (Afhttprequestoperation *operation,IDresponseobject) {        if(Success) {success (responseobject); }} failure:^ (Afhttprequestoperation *operation, Nserror *error) {        if(fail) {fail (); }    }];}

7. File upload-Randomly generated file name

+ (void) Postuploadwithurl: (NSString *) urlstr FILEURL: (Nsurl *) FILEURL success: (void(^) (IDResponseobject)) Success fail: (void(^) ()) fail{Afhttprequestoperationmanager*manager =[Afhttprequestoperationmanager Manager]; //Afhttpresponseserializer is the normal HTTP request response Result: NSData//when the requested return data is not json,xml,plist,uiimage, use Afhttpresponseserializer//For example, return a html,text ...//    //It 's actually the case that AFN didn't do anything with the response data.Manager.responseserializer =[Afhttpresponseserializer Serializer]; //Formdata is the subject of Afmultipartformdata .[Manager post:urlstr Parameters:nil constructingbodywithblock:^ (ID<AFMultipartFormData>formData) {                //uploading local files to the server//Nsurl *fileurl = [[NSBundle mainbundle] urlforresource:@ "Avatar 1.png" withextension:nil];[formData appendpartwithfileurl:fileurl name:@"UploadFile"Error:null]; } Success:^ (Afhttprequestoperation *operation,IDresponseobject) {//nsstring *result = [[NSString alloc] Initwithdata:responseobject encoding:nsutf8stringencoding];//        //NSLog (@ "complete%@", result);        if(Success) {success (responseobject); }} failure:^ (Afhttprequestoperation *operation, Nserror *error) {NSLog (@"Fatal error%@", error.localizeddescription); if(fail) {fail (); }    }];}

AFNetworking2.5 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.