如何测试 NSURLConnection 的失败?
另外,如何判断是否由于飞行模式或 WiFi 关闭而失败?在我的测试中,虽然弹出警报告诉用户他们需要打开 WiFi,但如果他们忽略它,我的应用程序就会坐在那里并旋转等待响应。
最佳答案
如果您的连接委托(delegate)是 self,您可以这样做:
self.myConnection = [[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self] autorelease];
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
if ([error code] == kCFURLErrorNotConnectedToInternet)
{
// if we can identify the error, we can present a more precise message to the user.
NSDictionary *userInfoDict = [NSDictionary dictionaryWithObject:@"No Connection Error"
forKey:NSLocalizedDescriptionKey];
NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain
code:kCFURLErrorNotConnectedToInternet
userInfo:userInfoDict];
[self handleError:noConnectionError];
}
else
{
// otherwise handle the error generically
[self handleError:error];
}
}
关于iphone - 测试 NSURLConnection 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2054117/