iOS Alamofire超时且无网络连接

问题描述 投票:5回答:1

即使没有网络连接,我也会收到超时错误。我正在使用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)")
        })
}
ios swift networking alamofire
1个回答
0
投票

由于您阅读的相同原因,它会引发超时。不值得在每次通话时进行检查。

© www.soinside.com 2019 - 2024. All rights reserved.