Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code=-1001 "The request timed out."

I am working on a Swift project which requires a lot of consumption of APIs. Everything is working fine but sometimes (1 in 20), I get Code=-1001 "The request timed out." error while calling the API.

I am using Alamofire. I am attaching the code to call API.

let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"    
request.HTTPBody = myUrlContents.dataUsingEncoding(NSUTF8StringEncoding)

request.timeoutInterval = 15

request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("\(myUrlContents.dataUsingEncoding(NSUTF8StringEncoding)!.length)", forHTTPHeaderField: "Content-Length")
request.setValue("en-US", forHTTPHeaderField: "Content-Language")

Alamofire.request(request)
      .validate()
      .responseJSON { [weak self] response in

      if response.result.isSuccess {
            if let result = response.result.value {
                  print("Result: \(result)")

                  completion(result: result as! NSDictionary)
            }
      }
      else {
            print(response.debugDescription)
       }
}

And the log is

[Request]: <NSMutableURLRequest: 0x18855620> { URL: http://....... (url)}
[Response]: nil
[Data]: 0 bytes
[Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSErrorFailingURLStringKey=http://.....(url) NSErrorFailingURLKey=http://.....(url), NSLocalizedDescription=The request timed out., _kCFStreamErrorDomainKey=4, NSUnderlyingError=0x18a08900 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102}}}
[Timeline]: Timeline: { "Request Start Time": 493582123.103, "Initial Response Time": 493582138.254, "Request Completed Time": 493582138.254, "Serialization Completed Time": 493582138.256, "Latency": 15.151 secs, "Request Duration": 15.151 secs, "Serialization Duration": 0.002 secs, "Total Duration": 15.153 secs }

I know I can increase the timeout period to avoid the error. But I want to know the actual reason why it is throwing the error. None of my API takes more than 2 seconds to return data. Then why it is showing latency of 15.151 seconds.

I am using LAMP stack on backend. Any help would be appreciated.

like image 476
Rahul Garg Avatar asked Aug 22 '16 18:08

Rahul Garg


1 Answers

I just encountered the same problem. I am using a GET request, and it turns out that using [:] is wrong. You have to use nil in GET request and [:] in POST request

like image 99
Jeff Zhang Avatar answered Oct 20 '22 17:10

Jeff Zhang