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