There are many network request functions in iOS, synchronous, asynchronous, through delegate asynchronous callbacks.
When doing a project, the Internet read a lot of other people's examples, found that there is not a simple, convenient asynchronous request encapsulation example. The encapsulation code I'm going to give here is asynchronous, the way the post is requested. Simple encapsulation via iOS native function. This package makes it easy to access HTTP servers, get data, and easily load network images asynchronously.
First, a new Httphelper class is created , encapsulated in this class, the encapsulated function name is called post, the parameter has the requested address URL, the requested parameter params, The function blockthat returns the callback after the data. The third parameter uses the block feature of Objective-c, which is to pass one function as an argument to another function. Interested can go and see.
The following first is the header file.
HttpHelper.h
#import <Foundation/Foundation.h>#import <UIKit/UIKit.h>#import" Reachability.h " @interface httphelper:nsobject+ (BOOL) Networkisok; // Check if the network is available + (void) Post: (NSString *) Url requestparams: (nsdictionary *)params Finishblock: (void (^) (Nsurlresponse *response, NSData *data, Nserror *connectionerror)) block; // POST Request Encapsulation @end
Next is the implementation file
//HTTPHELPER.M#import "HttpHelper.h"@implementationHttphelper//This function is a function that determines whether the network is available (WiFi or cellular data is available and returns YES)+(BOOL) networkisok{if([[[Reachability reachabilityforinternetconnection] currentreachabilitystatus]!=notreachable)&&([[reachability Reachabilityforlocalwifi] currentreachabilitystatus]!=notreachable)) { returnYES; }Else{ returnNO; }}//post asynchronous request encapsulation function+ (void) Post: (NSString *) URL requestparams: (Nsdictionary *)paramsFinishblock: (void(^) (Nsurlresponse *response, NSData *data, Nserror *connectionerror)) block{//Turn the incoming URL string into a URL addressNsurl *url =[Nsurl Urlwithstring:url]; //request initialization, where you can set some settings for caching, timeoutsNsmutableurlrequest *request =[Nsmutableurlrequest Requestwithurl:url Cachepolicy:nsurlre Questreloadignoringcachedata timeOutInterval: -]; //parse the request parameter, use Nsdictionary to save the parameter, through the custom function Parseparams parse it into a post format stringNSString *parseparamsresult = [Self parseparams:params]; NSData*postdata =[Parseparamsresult datausingencoding:nsutf8stringencoding]; [Request Sethttpmethod:@"POST"]; [Request Sethttpbody:postdata]; //Create a new queue (to open a new thread)Nsoperationqueue *queue = [NsoperationqueueNew]; //sends an asynchronous request, the data returned after the request is completed, and is invoked by the Completionhandler parameter[Nsurlconnection sendasynchronousrequest:request Queue:queue Completionhandler:block];//return result;}//parse the nsdictionary into the NSString string in post format+ (NSString *) Parseparams: (Nsdictionary *)params{nsstring*Keyvalueformat; Nsmutablestring*result = [nsmutablestringNew]; //instantiate a key enumerator to hold the dictionary keyNsenumerator *keyenum = [paramsKeyenumerator]; IDkey; while(key =[Keyenum Nextobject]) {Keyvalueformat= [NSString stringWithFormat:@"%@=%@&", key,[paramsValueforkey:key]]; [Result Appendstring:keyvalueformat]; NSLog (@"post () method parameter parse Result:%@", result); } returnresult;}@end
It's that simple. Here's a sample login to show you how it's used.
- (void) login{NSString*url =@"127.0.0.1/login.php"; NSString*username =@"Admin"; NSString*password =@"Root"; //Add parameterNsmutabledictionary *params= [NsmutabledictionaryNew]; [paramsSetvalue:username Forkey:@"Phone"]; [paramsSetvalue:password Forkey:@"Password"]; //have a network to send requests if([Httphelper Networkisok]) {//send the request, and get the data returned[Httphelper post:url Requestparams:paramsfinishblock:^ (Nsurlresponse *response, NSData *data, Nserror *connectionerror) {//The returned data is present, then the callback is executed. Sweet potato if(data) {//The child thread notifies the main thread that update Ui,selector is the function to execute, and data is the parameter passed to the function.//Login_callback processing the returned message, here is the simple output, login success[Self performselectoronmainthread: @selector (login_callback:) Withobject:data Waituntildone:yes]; }Else{NSLog (@"Invalid data"); } }]; }}//The login callback function first determines whether the received value is able to log on. If not, prompt the user. If you can log in, then processing segue to jump interface- (void) Login_callback: (ID) value{NSLog (@"Login Successful");}
The entire example is this, very simple, you can request a picture, and then execute the access image in the callback function, showing the operation in ImageView
iOS Development--post Asynchronous Network request encapsulation