NSURLConnection 进行网络请求时为同步请求方式占用主线程,但是避免了异步方式的数据不及时,不需要另外去刷新tableview;
用法: NSURL *url = [NSURLURLWithString:URLh];
NSURLRequest *request = [NSURLRequestrequestWithURL:url];
//UIWebView
// 建立网络请求建立网络连接指定请求的资源 代理(通过协议方法获取数据),进行异步请求(启动子线程请求)获取到数据后通过协议方法
_uc = [[NSURLConnectionalloc]initWithRequest:requestdelegate:self];
_dataArray = [[NSMutableArrayalloc]init];
NSLog(@"end");
afn 请求方式为异步,第三方另开子线程做数据请求,因为是异步,存在数据处理时间的不确定,需要另外刷新tableview 做数据更新;
用法:post
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManagermanager];
manager.responseSerializer.acceptableContentTypes = [NSSetsetWithObjects:@"text/html",nil];
NSDictionary *parameters =@{@"type":string};
[manager POST:kURL parameters:parameters success:^(AFHTTPRequestOperation *operation,id responseObject) {
} failure:^(AFHTTPRequestOperation *operation,NSError *error) {
}];
用法:get
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManagermanager];
manager.responseSerializer.acceptableContentTypes = [NSSetsetWithObjects:@"text/html",nil];
[manager GET:str parameters:nil success:^(AFHTTPRequestOperation * operation, id responseObject)
NSLog(@"%@",responseObject);
} failure:^(AFHTTPRequestOperation * operation, NSError * error) {
NSLog(@"-----------------------保存失败%@",error);
}];
NSURLSession
用法: NSURLSession *session = [NSURLSessionsharedSession];
// 可以通过工作模式获取响应的sesion对象
// [NSURLSession sessionWithConfiguration:<#(NSURLSessionConfiguration *)#>]
NSURLRequest *request = [NSURLRequestrequestWithURL:[NSURLURLWithString:URLh]];
// 创建task对象,第一个参数是请求对象 第二个参数是请求后的回调代码(data是服务器发送给客户端的数据 response是是服务器对请求的响应 error是错误对象)
_task = [session dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response, NSError *error) {
if (error == nil) {
NSDictionary*dic=[NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingMutableContainerserror:&error];
if (error ==nil) {
NSLog(@"%@",dic);
}
else
{;
NSLog(@"解析出错:%@",error.localizedDescription);
}
}
else
{
NSLog(@"%@",error.localizedDescription);
}
}];
[_task resume];
以上为个人使用时遇到的,记录下来,方便自己,如有错误,请允以纠正
另7.0以后的xcode
网络请求时需要在Info.plist中添加
NSAppTransportSecurity type Dictionary
在NSAppTransportSecurity下添加
NSAllowsArbitraryLoads type boolen 为yes