【问题标题】:iOS Alamofire Timeout and No Network ConnectioniOS Alamofire 超时和无网络连接
【发布时间】:2017-10-06 15:21:19
【问题描述】:

即使没有网络连接,我也会收到超时错误。我正在使用 Alamofire 发送请求。我已经看到有一些方法可以检查网络连接,例如How to use SCNetworkReachability in Swift,但从我读到的内容来看,最好发送请求而不是在每个请求之前检查网络连接。我的问题是为什么即使没有网络连接它也会抛出超时错误?有没有办法在两者之间进行检查,或者如果超时,我应该只检查网络可达性。

import Foundation
import Alamofire

var config = URLSessionConfiguration.default
var manager: SessionManager? = nil
var configured: Bool = false
let formatter = DateFormatter()

let postURL = URL(string: "http://httpbin.org/post")!

func postStatus(deviceID: String, status: Bool, latitude: Double, longitude: Double){
    print("\nPosting")

    if(!configured){
        print("Configuring")
        config.timeoutIntervalForResource = 4
        config.timeoutIntervalForRequest = 4
        manager = Alamofire.SessionManager(configuration: config)
        configured = true
    }else{
        print("Configured\n")
    }

    let postData: [String: Any] = ["deviceID": deviceID, "status": 0, "lat": String(latitude), "long": String(longitude), "timestamp": getCurrentTime()]

    manager?.request(postURL, method: HTTPMethod.post, parameters: postData, encoding: JSONEncoding.default, headers: nil)
        .responseJSON(completionHandler: { response in

            guard response.result.error == nil else{
                let error = response.result.error!

                if let err = error as? URLError {
                    switch err.code {
                    case .notConnectedToInternet:
                        print("No Internet Connection")
                    case .timedOut:
                        print("Request Time Out")
                    case .networkConnectionLost:
                        print("Connection Lost")
                    default:
                        print("Default Error")
                        print(err)
                    }
                }
                return
            }

            guard let json = response.result.value as? [String: Any] else{
                print("Didn't get a response")
                print("Error: \(response.result.error ?? "Json Default Error" as! Error)")
                return
            }

            print("Response From Server: \(json)")
        })
}

【问题讨论】:

  • 我也有同样的问题。对于我的一个 POST 请求,它正确返回 .notConnectedToInternet 但对于另一个 POST 请求,它挂起并返回。超时

标签: ios swift networking alamofire


【解决方案1】:

由于您已阅读的相同原因,它会引发超时。不值得每次调用都检查。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多