使用NSURLConnection的网络请求,最好定义一个类方法,在主线程中直接调用类方法获取请求到的网络数据
//构建类方法--请求网络
+ (void)requestData:(NSString *)urlStr
httpMethod:(NSString *)method
params:(NSMutableDictionary *)params
comletionHandle:(void (^)(id result))block
{
//1.构建URL
urlStr = [BASE_URL stringByAppendingString:urlStr];
NSURL *url = [NSURL URLWithString:urlStr];
//2.request构建
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.timeoutInterval = 60;
request.HTTPMethod = method;
//判断请求方式
if ([method isEqualToString:@"GET"]) {
//往URL后直接拼接
NSMutableString *paramsStr = [[NSMutableString alloc]initWithString:@"?"];
//拼接样式
//循环拼接参数字典
for (int i = 0; i < params.count; i ++) {
NSString *key = params.allKeys[i];
NSString *value = params[key];
//开始拼接=
[paramsStr appendFormat:@"%@=%@",key,value];
//拼接&符号
//最后一个不再用&符号拼接
if (i < params.count-1) {
[paramsStr appendFormat:@"&"];
}
}
//得到拼接后的URL(将主URL与拼接的URL 拼接在一起得到完整的URL)
request.URL = [NSURL URLWithString:[urlStr stringByAppendingString:paramsStr]];
}else if ([method isEqualToString:@"POST"]){
//将参数添加到请求体中
NSMutableString *paramsStr = [[NSMutableString alloc]initWithString:@""];
for (int i = 0; i < params.count; i ++) {
NSString *key = params.allKeys[i];
NSString *value = params[key];
//开始拼接
[paramsStr appendFormat:@"%@=%@",key,value];
if (i < params.count - 1) {
[paramsStr appendFormat:@"&"];
}
}
//添加到请求体中
//将字符串转化为数据
NSData *data = [paramsStr dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = data;
}
//3.开始请求网络
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError) {
NSLog(@"error----%@",connectionError);
return ;
}
//成功获取数据
//开始解析数据
id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//返回数据
dispatch_async(dispatch_get_main_queue(), ^{
block(result);
});
}];
}
本文出自 “UI中的控件的应用” 博客,请务必保留此出处http://10554206.blog.51cto.com/10544206/1693237
原文:http://10554206.blog.51cto.com/10544206/1693237