Ios 处理异步网络调用中的错误/数据
在上面的异步网络调用中,我检查状态代码是否不是200,并假设这是一个错误。这是在IOS中处理网络呼叫中的错误/数据处理的正确方法吗Ios 处理异步网络调用中的错误/数据,ios,objective-c,Ios,Objective C,在上面的异步网络调用中,我检查状态代码是否不是200,并假设这是一个错误。这是在IOS中处理网络呼叫中的错误/数据处理的正确方法吗 如果http状态码不是200,那么异步请求的NSError总是非nill,如果http状态码是200,那么NSERLOR总是非nill?据我所知,如果您的NSURLConnection返回错误,则表示没有收到服务器的响应 如果服务器发送响应,无论是什么HTTP代码,NSUrlConnection都不会给您任何错误(返回的错误为零) 实际上,NSURLError.h列
如果http状态码不是200,那么异步请求的NSError总是非nill,如果http状态码是200,那么NSERLOR总是非nill?据我所知,如果您的
NSURLConnection
返回错误,则表示没有收到服务器的响应
如果服务器发送响应,无论是什么HTTP代码,NSUrlConnection
都不会给您任何错误(返回的错误为零)
实际上,NSURLError.h
列出了与NSURLConnection相关的所有错误,它们可以是,例如:
[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;
}];
因此,这就是您从网络呼叫中收到的NSError
对象中可能会发现的错误类型
相反,如果您有一个HTTP错误,这意味着至少可以访问服务器,服务器会回复,等等
您还可以在网络分层体系结构的上下文中看到这一点,其中HTTP是一种应用程序协议,HTTP错误仅在该级别具有意义
另一方面,
NSURLConnection
在应用程序级别之下的传输级别工作。因此,应用程序级别的错误对它没有任何意义,只是从一端透明地“传输”到另一端。如果我没有弄错,则如果发生错误,completionHandler的N错误将为非空。从那里您可以获得相关的错误代码、域和描述。如果NSError不为NULL,则可以检查它是哪一个代码,然后继续。
NSURLErrorTimedOut
NSURLErrorCannotConnectToHost
NSURLErrorNetworkConnectionLost
NSURLErrorNotConnectedToInternet