Timeout interval not set for POST requests on iOS

1.5k views Asked by At

I have a timeOutInterval set to 30 seconds on all my requests via this code:

class DefaultAlamofireSession: Alamofire.Session {
    static let shared: DefaultAlamofireSession = {
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 30
        configuration.timeoutIntervalForResource = 30
        return DefaultAlamofireSession(configuration: configuration)
    }()
}

While testing, I noticed that only my GET requests get timed out at 30 seconds. My POST requests are still using the default interval which is 60 seconds.

Can anyone explain why and possibly tell me how I can make the POST requests also time out at 60 seconds?

Thanks a lot, Paprika

1

There are 1 answers

1
Jon Shier On

URLSessionConfiguration.timeoutIntervalForRequest does not do what you think it does. From Apple's docs:

This property determines the request timeout interval for all tasks within sessions based on this configuration. The request timeout interval controls how long (in seconds) a task should wait for additional data to arrive before giving up. The timer associated with this value is reset whenever new data arrives. When the request timer reaches the specified interval without receiving any new data, it triggers a timeout.

So that property only controls the timeout between chunks of response Data. That's not typically what you want. Instead, you want to set the URLRequest.timeoutInterval directly, which does more of what you want.

If during a connection attempt the request remains idle for longer than the timeout interval, the request is considered to have timed out. The default timeout interval is 60 seconds.

As you can see, this timeout applies to the connection attempt, which is what most people think of as a request's timeout.

You can customize this value in Alamofire by applying a RequestAdapter to your custom Session. Or, you can use the requestModifier closure that available on the various request* methods.