问题
I use NSURLConnection's
sendSynchronousRequest:returningResponse:error:
method (in a separate NSOperation
thread) to connect to external server to retreive data. How do I know if the operation ended timed out, or some other network error?
回答1:
If there was an error, the error parameter will be non-nil when sendSynchronousRequest:returningResponse:error:
returns.
You can retrieve the error code by checking the value returned by [NSError code]
. The error code for time out is NSURLErrorTimedOut
.
For instance:
NSError *error = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]
if (error.code == NSURLErrorTimedOut) {
// Handle time out here
}
回答2:
Check this extension
:
extension Error {
var isConnectivityError: Bool {
guard _domain == NSURLErrorDomain else { return false }
let connectivityErrors = [NSURLErrorTimedOut,
NSURLErrorNotConnectedToInternet,
NSURLErrorNetworkConnectionLost,
NSURLErrorCannotConnectToHost]
return connectivityErrors.contains(_code)
}
}
You can check in doc for other errors in NSURLError
domain to expand your connectivityErrors
array.
回答3:
You may present an alert to the user and pass the error parameter in sendSynchronousRequest:returningResponse:error:
to the alert's message.
the code will be something like this:
[NSURLConnection sendSynchronousRequest: req returningResponse: &response error: &error];
if (error)
{
UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Error" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}
Hope it helps!!
来源:https://stackoverflow.com/questions/12818887/how-to-detect-if-nsurlconnections-sendsynchronousrequestreturningresponseerro