Handle No Internet Connection Error Before Try to Parse the Result in Alamofire

后端 未结 7 1840
旧巷少年郎
旧巷少年郎 2020-12-30 03:04

How should I handle if there is an error occurs when there is no internet connection in Alamofire. I tried checking if data is nil or not but it does not work.

Below

7条回答
  •  礼貌的吻别
    2020-12-30 03:52

    Swift 3 Solution

    Assuming you have an Error instance you can do the following:

    if let err = error as? URLError, err.code  == URLError.Code.notConnectedToInternet
    {
        // No internet
    }
    else
    {
        // Other errors
    }
    

    You simply cast error into a URLError. This works since URLError implements the Error protocol. Here is a quote from the apple documentation for reference:

    URLError: Describes errors in the URL error domain.

    Once you have a URLError instance you can simply compare its code property, which is a URLError.Code enum, against the any relevant enum cases (in our example URLError.Code.notConnectedToInternet).

提交回复
热议问题