我不会依靠非零的错误来表明发生错误。
我一直在用错误在Ben的回答说明检查,但我相信它是产生在某些情况下,假阳性/虚假错误。
按本SO answer,我改变使用方法的结果来确定是否成功/失败。然后(并且只有)然后检查错误指针以获取失败的细节。
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
/* Return Value
The downloaded data for the URL request. Returns nil if a connection could not be created or if the download fails.
*/
if (response == nil) {
// Check for problems
if (requestError != nil) {
...
}
}
else {
// Data was received.. continue processing
}
该方法将避免对下载过程中发生的错误没有造成失败的反应。我认为在下载过程中可能会遇到在框架内处理的非关键性错误,并且它们具有将错误指针设置为错误对象的副作用。
举例来说,我已经越来越从已下载的应用程序,似乎在URL连接的深加工发生用户报告POSIX的错误。
此代码是用来报告错误:
NSString *errorIdentifier = [NSString stringWithFormat:@"(%@)[%d]",requestError.domain,requestError.code];
[FlurryAPI logError:errorIdentifier message:[requestError localizedDescription] exception:nil];
而出现错误报告:
Platform: iPhone
Error ID: (NSPOSIXErrorDomain)[22]
Msg: Operation could not be completed. Invalid argument
映射,早..
requestError.domain = NSPOSIXErrorDomain
requestError.code = 22
[requestError localizedDescription] = Operation could not be completed. Invalid argument
我的一切。能够挖掘,是错误代码22是EINVAL
,但这并没有产生任何进一步的细节。
其他错误,我得到的是从NSURL域,这点我完全不同的网络条件下,预计有:
NSURLErrorTimedOut
NSURLErrorCannotConnectToHost
NSURLErrorNetworkConnectionLost
NSURLErrorNotConnectedToInternet
+others
确保初始化错误和应对零,我得到EXC_BAD_ACCESS错误,直到我发现这个答案。谢谢+1! – keegan3d 2011-01-08 07:33:18
在测试错误之前,您确实需要测试结果。从文档*“如果无法创建连接或下载失败,则返回nil”* http://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference html的#// apple_ref/OCC/CLM/NSURLConnection的/ sendSynchronousRequest:returningResponse:错误: – ohhorob 2011-07-23 19:28:23
可可[保证](http://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ErrorHandlingCocoa/CreateCustomizeNSError/CreateCustomizeNSError 。html#// apple_ref/doc/uid/TP40001806-CH204-SW1)如果该方法失败,错误对象将是有效的;如果方法成功,它不_保证错误对象将是'nil'。在使用错误之前,您必须检查直接返回值。 – 2011-07-23 20:24:35