2013-10-11 102 views
0
[NSURLConnection sendAsynchronousRequest:request 
            queue:[NSOperationQueue mainQueue] 
         completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) 
{ 

    NSDictionary * dictionary = nil; 
    NSError * returnError = nil; 
    NSString * errorCode = nil; 
    NSString * errorText = nil; 
    NSInteger newErrorCode = 0; 

    if([data length] >= 1) { 
     dictionary = [NSJSONSerialization JSONObjectWithData: data options: 0 error: nil]; 
    } 

    if(dictionary == nil) { 

     newErrorCode = -1; 
     errorText = @"There was an unexpected error."; 
     NSMutableDictionary* details = [NSMutableDictionary dictionary]; 
     [details setValue: errorText forKey: NSLocalizedDescriptionKey]; 
     returnError = [NSError errorWithDomain: AppErrorDomain code: newErrorCode userInfo: details]; 

     responseHandler(nil, returnError); 

     return; 
    } 

    NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode]; 

    if(statusCode != 200) 
    { 
     if(dictionary != nil) { 
      if([dictionary objectForKey: @"error_code"] != nil) { 
       errorCode = [dictionary objectForKey: @"error_code"]; 
      } 

      if([dictionary objectForKey: @"error_description"] != nil) { 
       errorText = [dictionary objectForKey: @"error_description"]; 
      } 
     } 

     if(errorCode == nil) 
     { 
      newErrorCode = UnexpectedError; 

      errorText = NSLocalizedString(@"There was an unexpected error.", @"There was an unexpected error."); 

     } 
     else { 
      newErrorCode = [errorCode intValue]; 
     } 

     NSMutableDictionary* details = [NSMutableDictionary dictionary]; 
     [details setValue: errorText forKey: NSLocalizedDescriptionKey]; 
     returnError = [NSError errorWithDomain: APPErrorDomain code: newErrorCode userInfo: details]; 
    } 

    responseHandler(dictionary, returnError); 

    return; 

}]; 

在我上面的異步網絡電話,我請檢查狀態代碼不是200,並且假設是錯誤的。這是在IOS中處理網絡調用中的錯誤/數據處理的正確方法嗎?處理錯誤/中 - 異步網絡數據調用

我們總是可以假設,如果http狀態碼不是200,那麼異步請求中的NSError總是非空的,如果是200則是否爲nill?

+0

如果我沒有弄錯,如果發生錯誤,completionHandler的NSError將爲非NULL。從那裏你可以得到相關的錯誤代碼,域和描述。如果NSError不是NULL,那麼你可以檢查它是從那裏繼續的代碼。 – Jonathan

回答

0

據我所知,如果你的NSURLConnection返回一個錯誤,比這意味着沒有收到服務器的響應。

如果服務器發送它的響應,無論HTTP代碼,NSUrlConnection不會給你任何錯誤(返回的錯誤將爲零)。

事實上,相關NSURLError.h列出了所有錯誤NSURLConnection的,他們就可以了,例如:

NSURLErrorTimedOut 
NSURLErrorCannotConnectToHost 
NSURLErrorNetworkConnectionLost 
NSURLErrorNotConnectedToInternet 

所以,這是你從接收回來的那種,你可以期望在NSError對象發現錯誤的你網絡通話。

相反,如果你有一個HTTP錯誤,這意味着至少該服務器可以達成,它回答說,等

你也可以看到這個網絡分層架構的背景下,因此HTTP是一種應用程序協議,HTTP錯誤僅在該級別有意義。

另一方面,NSURLConnection適用於運輸級別,低於應用級別。因此,應用程序級別的錯誤對它沒有任何意義,只是從一端透明地「運輸」到另一端。