有三種類型的問題,你可能要檢查:
連接錯誤:檢查以確保連接沒有失敗;如果確實失敗,則數據將爲nil
,並且將填充NSError
對象;典型的原因是URL中的服務器名稱無效,服務器關閉,或根本沒有互聯網連接);
HTTP錯誤:如果做一個HTTP請求,要檢查Web服務器成功報道檢索頁/資源,即您收到的200 HTTP狀態代碼;一個錯誤情況的例子可能是一個404 - 找不到的錯誤(更多完整列表見HTTP Status Code Definitions);和
服務器代碼中的錯誤:檢查,以確保服務器具有有效的JSON迴應,即檢查是否收到可以成功地解析爲JSON響應(你要確保有一個在服務器沒問題生成JSON的代碼,例如服務器代碼中的錯誤)。
因此:
NSURLRequest *request = nil;
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (!data) {
NSLog(@"%s: sendSynchronousRequest error: %@", __FUNCTION__, error);
return;
} else if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSLog(@"%s: sendSynchronousRequest status code != 200: response = %@", __FUNCTION__, response);
return;
}
}
NSError *parseError = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (!dictionary) {
NSLog(@"%s: JSONObjectWithData error: %@; data = %@", __FUNCTION__, parseError, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
return;
}
// now you can use your `dictionary` object
顯然,如果它是NSArray的,改變上述JSONObjectWithData
線返回陣列,但概念是相同的。
或者,更好,使用異步連接(如你不應該使用在主隊列同步連接):
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!data) {
NSLog(@"%s: sendAynchronousRequest error: %@", __FUNCTION__, connectionError);
return;
} else if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSLog(@"%s: sendAsynchronousRequest status code != 200: response = %@", __FUNCTION__, response);
return;
}
}
NSError *parseError = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (!dictionary) {
NSLog(@"%s: JSONObjectWithData error: %@; data = %@", __FUNCTION__, parseError, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
return
}
// now you can use your `dictionary` object
}];
// Note, with asynchronous connection, do not try to use `data`
// or the object you parsed from theJSON after the block, here.
// Use it above, inside the block.
來源
2014-01-08 12:56:44
Rob
'sendSynchronousRequest:returningResponse:ERROR'我想'NSError'可以放,或檢查如果'NSData'不是零可以幫助... – Larme
是的,你可以實際檢查'錯誤'(儘管我知道這是對「沒有淨」編程原則)。 –