使用Alamofire的API调用有时会返回连接失败错误

时间:2018-04-05 10:00:02

标签: ios swift api alamofire

我正在使用alamofire进行api通话。请求调用每次都会成功阻塞,但有时会有相同的请求,呼叫将失败并且出现错误"网络连接丢失"。由于网络连接没有问题,我无法找到特定问题的解决方案。这是我的代码 -

let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 120
        manager.request(url, method: .post, parameters: requestDictionary ?? [:], encoding: JSONEncoding.default).responseJSON(completionHandler: { (response) in
            switch response.result {

            case .success:
                KVNProgress.dismiss()
                let jsonString: String = String(data: response.data!, encoding: String.Encoding.utf8)!
                print(jsonString)
                let dict : [String : Any ] = response.result.value! as! [String : Any]
                let msg = dict["Message"] as? String
                if msg == "Session id is not valid." {

                    //logout process…   

                    }, onCancelClick: {

                    })

                }else{
                    success(response.result.value! as AnyObject)
                }

            case .failure(let error):
                KVNProgress.dismiss()
                print("Request failed with error: \(error.localizedDescription)")
                failure(“Unexpected error”)
            }
        })

提前致谢。 :)

我的代码位于我已经检查过互联网连接的区块内 -

 if(Utilities.checkInternetConnection())
   {
        // My previous code
    }

    else
    {
        connectionFailed(Constant.serverAPI.errorMessages.kNoInternetConnectionMessage)
    }

1 个答案:

答案 0 :(得分:0)

我也有这个问题,很多时候API调用返回连接失败错误。

我通过捕获连接失败错误并从连接失败关闭再次调用API错误来解决它