7

I am getting a timeout error even if there is no network connection. I am using Alamofire to send requests. I have seen there are ways to check network connection such as at How to use SCNetworkReachability in Swift but from what I read it is better to send the request rather than checking for a network connection before each one. My question is why is it throwing a timeout error even if there is no network connection? Is there a way to check between the two or should I just check network reachability if there is a timeout.

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)")
        })
}
Community
  • 1
  • 1
Ubarjohade
  • 471
  • 6
  • 21
  • I have the same issue. For one of my POST request it correctly returns .notConnectedToInternet but for the other POST request it hangs and return . timedOut – Michał Ziobro Jun 18 '18 at 10:23

1 Answers1

-1

It is throwing a timeout for the same reason you have read. It is not worth checking on every call.

sweetfa
  • 5,457
  • 2
  • 48
  • 62