#import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "Reachability.h" @interface HttpHelper : NSObject + (BOOL)NetWorkIsOK;//检查网络是否可用 + (void)post:(NSString *)Url RequestParams:(NSDictionary *)params FinishBlock:(void (^)(NSURLResponse *response, NSData *data, NSError *connectionError)) block;//post请求封装 @end
接下来是实现文件
// HttpHelper.m #import "HttpHelper.h" @implementation HttpHelper //这个函数是判断网络是否可用的函数(wifi或者蜂窝数据可用,都返回YES) + (BOOL)NetWorkIsOK{ if( ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable) && ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable) ){ return YES; }else{ return NO; } } //post异步请求封装函数 + (void)post:(NSString *)URL RequestParams:(NSDictionary *)params FinishBlock:(void (^)(NSURLResponse *response, NSData *data, NSError *connectionError)) block{ //把传进来的URL字符串转变为URL地址 NSURL *url = [NSURL URLWithString:URL]; //请求初始化,可以在这针对缓存,超时做出一些设置 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20]; //解析请求参数,用NSDictionary来存参数,通过自定义的函数parseParams把它解析成一个post格式的字符串 NSString *parseParamsResult = [self parseParams:params]; NSData *postData = [parseParamsResult dataUsingEncoding:NSUTF8StringEncoding]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:postData]; //创建一个新的队列(开启新线程) NSOperationQueue *queue = [NSOperationQueue new]; //发送异步请求,请求完以后返回的数据,通过completionHandler参数来调用 [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:block]; // return result; } //把NSDictionary解析成post格式的NSString字符串 + (NSString *)parseParams:(NSDictionary *)params{ NSString *keyValueFormat; NSMutableString *result = [NSMutableString new]; //实例化一个key枚举器用来存放dictionary的key NSEnumerator *keyEnum = [params keyEnumerator]; id key; while (key = [keyEnum nextObject]) { keyValueFormat = [NSString stringWithFormat:@"%@=%@&",key,[params valueForKey:key]]; [result appendString:keyValueFormat]; NSLog(@"post()方法参数解析结果:%@",result); } return result; } @end
就是这么简单。下面用 登录的例子 给大家演示一下是怎么用的。
- (void)login{ NSString *url = @"127.0.0.1/login.php"; NSString *userName = @"admin"; NSString *password = @"root"; //加入参数 NSMutableDictionary *params = [NSMutableDictionary new]; [params setValue:userName forKey:@"phone"]; [params setValue:password forKey:@"password"]; //有网络才发送请求 if([HttpHelper NetWorkIsOK]){ //发送请求,并且得到返回的数据 [HttpHelper post:url RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) { //传回来的数据存在,则执行改回调甘薯 if(data){ //子线程通知主线程更新UI,selector中是要执行的函数,data是传给这个函数的参数 //login_callBack就处理返回来的消息,这里就简单的输出,登录成功 [self performSelectorOnMainThread:@selector(login_callBack:) withObject:data waitUntilDone:YES]; }else{ NSLog(@"无效的数据"); } }]; } } //登录的回调函数,首先判断接收的值是不是能登录。若不能,则提示用户。若能登录,则处理segue来跳转界面 - (void)login_callBack:(id)value{ NSLog(@"登录成功"); }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/yangchen9931/article/details/46712087