通過一個簡單的聯網獲取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];
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];