Test NSURLConnection failure

2019-05-24 07:24发布

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条回答
做个烂人
2楼-- · 2019-05-24 07:38

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];
    }
}
查看更多
登录 后发表回答