Test NSURLConnection failure

可紊 提交于 2019-12-10 11:02:39

问题


How can you test a failure of NSURLConnection?

Also, how do you tell if it failed due to airplane mode or WiFi being turned off? In my tests, while the alert pops up telling the user they need to turn on WiFi, if they ignore it my App just sits there and spins waiting for a response.


回答1:


If your connection's delegate is self, you can something like this:

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];
    }
}


来源:https://stackoverflow.com/questions/2054117/test-nsurlconnection-failure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!