2

如何测试 NSURLConnection 的失败?

另外,您如何判断它是否由于飞行模式或WiFi被关闭而失败?在我的测试中,虽然弹出警报告诉用户他们需要打开 WiFi,但如果他们忽略它,我的应用程序只会坐在那里旋转等待响应。

4

1 回答 1

4

如果您的连接的委托是自我,您可以这样:

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];
    }
}
于 2010-01-13T03:14:00.487 回答