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]; 



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