How do i handle HTTP load failed (error code: -100

2019-05-05 08:21发布

问题:

I created on app using swift 4 and Xcode 9. when I login into my app I send a request and successful login on result which come from json. But when I switch my internet of my phone it crashed and give me this error

HTTP load failed (error code: -1009 [1:50])

So how do I handle this error and give popup or any warning to user to check your internet connection without app crashing.

回答1:

Swift 4, Xcode 10.1 You can access to the error code:

class ViewController1: UIViewController, URLSessionDataDelegate {
    ...    
    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        if error != nil {
            debugPrint("error message: \(error!)")
            debugPrint("code: \(error!._code)")
            if error!._code == -1009 {
                ...
            }
        }
    }
}

See also source code at: https://stackoverflow.com/a/53402801/966789