iOS 7开发之NSURLSession vs NSURLConnection

通过一个简单的联网获取JSON数据并将其解析 

举个例子 获取伦敦的天气数据

NSString*londonWeatherUrl =@"http://api.openweathermap.org/data/2.5/weather?q=London,uk"

//这里是使用NSURLConnection联网的方法

NSURLRequest*request = [NSURLRequestrequestWithURL:[NSURLURLWithString:londonWeatherUrl]];

[NSURLConnectionsendAsynchronousRequest:requestqueue:[NSOperationQueuemainQueue]completionHandler:^(NSURLResponse*response,

NSData*data,

NSError*connectionError) {// handle response

}] 


//通过NSURLSession联网的方法

NSURLSession*session = [NSURLSession sharedSession];
[[session
dataTaskWithURL:[NSURLURLWithString:londonWeatherUrl]

completionHandler:^(NSData*data,NSURLResponse*response,

NSError*error) {

// handle response

}] resume]; 


// Use AFNetworking

NSURLRequest *request = [NSURLRequest requestWithURL:
[
NSURL URLWithString:londonWeatherUrl]];

AFJSONRequestOperation *operation =
[
AFJSONRequestOperation JSONRequestOperationWithRequest:request

success:^(NSURLRequest *request,NSHTTPURLResponse *response,

id JSON) {// handle response

} failure:nil];[operation start]; 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章