11

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.

Rahul Garg
  • 153
  • 1
  • 1
  • 12
  • Do you see the request that times out being received on your server? How long is the server taking to process it? – Phillip Mills Aug 22 '16 at 19:06
  • Are you hitting the exact same URL every time? It seems unlikely to me that is a problem with your app. More likely, you really do you have a scenario where your API is slow. – Mike Taverne Aug 22 '16 at 19:30
  • Did you try to make this request on a REST client? Does it timeout? – quant24 Aug 22 '16 at 20:50
  • 2
    @quant24 that's the issue. It's throwing this error only while i hit it via iOS device. Even on Android, everything is working fine. – Rahul Garg Aug 22 '16 at 21:31
  • 1
    @MikeTaverne i hit the exact url everytime to check if error is resolved. But the issue is not one API specific. The error is shown across the app hitting any API on iOS device. – Rahul Garg Aug 22 '16 at 21:34
  • 1
    I also encountered the same issue. The problem is the API hit never reaches the backend, maybe when the network switch happens or the app goes in background before this request is fired by iOS, this occurs. – Ankit Srivastava Jan 15 '17 at 07:40

2 Answers2

10

I had got the error with Code=-1001 “The request timed out.”. I tried a few things. Nothing worked. Finally I found out that the problem was in my parameters that I'm sending in the request body to the server which were of wrong format(value was fine but type was wrong). Thats why the request was timing out coz the server wasn't able to process it. You can check that up if nothing else works for u.

Priyanka
  • 442
  • 1
  • 5
  • 13
  • 5
    thanks man! Just spent a couple of hours trying to figure out what's wrong with a simple request using `Moya`+`Alamofire`. The issue was empty parameters dictionary `[ : ]` instead of `nil` – medvedNick Jul 10 '17 at 16:23
7

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

Jeff Zhang
  • 140
  • 1
  • 7