IOS development-post Asynchronous Network request Encapsulation

Source: Internet
Author: User

IOS development-post Asynchronous Network request Encapsulation

# Import
 
  
# Import
  
   
# Import Reachability. h @ interface HttpHelper: NSObject + (BOOL) NetWorkIsOK; // check whether the Network is available + (void) post :( NSString *) Url RequestParams :( NSDictionary *) params FinishBlock :( void (^) (NSURLResponse * response, NSData * data, NSError * connectionError) block; // post request encapsulation @ end
  
 

The following is the implementation file

// HttpHelper. m # import HttpHelper. h @ implementation HttpHelper // This function is used to determine whether the Network is available (YES is returned for wifi or cellular data) + (BOOL) netWorkIsOK {if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus]! = NotReachable) & ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus]! = NotReachable) {return YES;} else {return NO;} // post asynchronous request encapsulation Function + (void) post :( NSString *) URL RequestParams :( NSDictionary *) params FinishBlock :( void (^) (NSURLResponse * response, NSData * data, NSError * connectionError )) block {// convert the passed URL string to the URL address NSURL * url = [NSURL URLWithString: URL]; // request initialization, which can be used for caching, set NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url cachePolicy: NSURLRequestReloadIgnoringCacheData timeoutInterval: 20]; // parse request Parameters and use NSDictionary to store parameters, use the custom function parseParams to parse it into a post-Format String NSString * parseParamsResult = [self parseParams: params]; NSData * postData = [parseParamsResult dataUsingEncoding: NSUTF8StringEncoding]; [request setHTTPMethod: @ POST]; [request setHTTPBody: postData]; // create a new queue (enable a new thread) NSOperationQueue * queue = [NSOperationQueue new]; // send an asynchronous request. After the request is complete, call [NSURLConnection sendAsynchronousRequest: request queue: queue completionHandler: block] using the completionHandler parameter; // return result ;} // parse NSDictionary into a post-format NSString + (NSString *) parseParams :( NSDictionary *) params {NSString * keyValueFormat; NSMutableString * result = [NSMutableString new]; // instantiate a key enumerator to store the key NSEnumerator * keyEnum = [params keyEnumerator]; id key; while (key = [keyEnum nextObject]) {keyValueFormat = [NSString stringWithFormat: @ % @ = % @ &, key, [params valueForKey: key]; [result appendString: keyValueFormat]; NSLog (@ post () method parameter resolution result: % @, result);} return result;} @ end

That's simple. The following example shows how to use logons.

-(Void) login {NSString * url = @ 127.0.0.1/login. php; NSString * userName = @ admin; NSString * password = @ root; // Add the parameter NSMutableDictionary * params = [NSMutableDictionary new]; [params setValue: userName forKey: @ phone]; [params setValue: password forKey: @ password]; // if ([HttpHelper NetWorkIsOK]) {// send the request and obtain the returned data [HttpHelper post: url RequestParams: params FinishBlock: ^ (NSURLResponse * response, N SData * data, NSError * connectionError) {// if the returned data exists, execute the modify callback sweet potato if (data) {// The subthread notifies the main thread to update the UI, in selector, it is the function to be executed, and data is the parameter/login_callBack passed to this function to process the returned message. Here, it is a simple output, and the logon is successful. [self login mselecw.mainthread: @ selector (login_callBack :) withObject: data waitUntilDone: YES];} else {NSLog (@ invalid data) ;}}} // callback function for logon, first, determine whether the received value can be logged on. If not, the system prompts the user. If you can log on to the console, you can jump to the interface using the seue-(void) login_callBack :( id) value {NSLog (@ logon successful );}

 

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.