How to detect if NSURLConnection's sendSynchronousRequest:returningResponse:error: ended up being timed out or other error

与世无争的帅哥 提交于 2019-12-21 14:59:12

问题


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

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