NSURLSession: How to increase time out for URL requests?
ObjC
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfig.timeoutIntervalForRequest = 30.0;
sessionConfig.timeoutIntervalForResource = 60.0;
Swift
let sessionConfig = URLSessionConfiguration.default
sessionConfig.timeoutIntervalForRequest = 30.0
sessionConfig.timeoutIntervalForResource = 60.0
let session = URLSession(configuration: sessionConfig)
What docs say
timeoutIntervalForRequest
and timeoutIntervalForResource
specify the timeout interval for the request as well as the resource.
timeoutIntervalForRequest
- The timeout interval to use when waiting
for additional data. 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.
timeoutIntervalForResource
- The maximum amount of time that a
resource request should be allowed to take. This value controls how
long to wait for an entire resource to transfer before giving up. The
resource timer starts when the request is initiated and counts until
either the request completes or this timeout interval is reached,
whichever comes first.
Based on NSURLSessionConfiguration Class Reference
NSURLSession sharedSession default timeout
There are two timeouts for URL sessions. The first is the maximum time allowed between receiving new data. This is called the timeoutIntervalForRequest
. The second is the maximum time the entire request is allowed to take (assuming it's regularly receiving new data). This is called the timeoutIntervalForResource
.
Both of these timeouts are configured by default using NSURLSessionConfiguration
, and can be overridden on the NSURLRequest
.
The default timeoutIntervalForRequest
is 60 seconds.
The default timeoutIntervalForResource
is 7 days.
Request Timeout NSURLSession
You can't modify your request because for some reason you went with immutable option. Since NSMutableURLRequest is a subclass of NSURLRequest you can use the very same initializer init(URL:cachePolicy:timeoutInterval:)
to create an mutable instance and set default timeout. And then configure (mutate) this request as you need.
let request = NSMutableURLRequest(URL: url!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0)
NSURLSession set request timeout accurately
It can be used, but it rarely makes sense to do so.
The expected user experience from an iOS app is that when the user asks to download or view some web-based resource, the fetch should continue, retrying/resuming as needed, until the user explicitly cancels it.
That said, if you're talking about fetching something that isn't requested by the user, or if you are fetching additional optional data that you can live without, adding a resource timeout is probably fine. I'm not sure why you would bother to cancel it, though. After all, if you've already spent the network bandwidth to download half of the data, it probably makes sense to let it finish, or else that time is wasted.
Instead, it is usually better to time out any UI that is blocked by the fetch, if applicable, but continue fetching the request and cache it. That way, the next time the user does something that would cause a similar fetch to occur, you already have the data.
The only exception I can think of would be fetching video fragments or something similar, where if it takes too long, you need to abort the transfer and switch to a different, lower-quality stream. But in most apps, that should be handled by the HLS support in iOS itself, so you don't have to manage that.
NSURLSession timeout
You cannot change the timeout on the sharedSession
or a sessions configuration
property. You have to set the timeout when the session is created. See this for an example of how to create a session and its timeout: https://stackoverflow.com/a/30427187/78496
iOS Swift : How to find if an NSURLSession has timed out
You can call method this way:
let request = NSURLRequest(URL: NSURL(string: "https://evgenii.com/")!)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
if error != nil {
if error?.code == NSURLErrorTimedOut {
println("Time Out")
//Call your method here.
}
} else {
println("NO ERROR")
}
}
task.resume()
Handle URLSession timeout
You can cast your error to URLError
type and then use the code
property to safely check if it's a session timeout error:
if (err as? URLError)?.code == .timedOut {
// Handle session timeout
}
Related Topics
Where to Find a Clear Explanation About Swift Alert (Uialertcontroller)
How to Use Nsuserdefaults to Store an Array of Custom Classes in Swift
How to Handle Local Notification When App Has Been Terminated
Import Xctest into a Dynamic Framework
How to Add .Plist File to All Targets in Xcode
Why am I Getting an Error Regarding Bolts Framework and Facebooksdk When I'm Not Even Using Bolts
Why Doesn't iOS System Sound Play in Simulator
How to Make an API Call When the User Terminates the App
Get All List of Uiviewcontrollers in iOS Swift
iOS Swift Connect Wifi Programmatically and Distinguish Between Bad Password and No Wifi in Range
Programmatically Set Uipageviewcontroller Transition Style to Scroll
Change Title of a Navigation Bar Button Item
How to Completely Reload a View So That Viewdidload Gets Run Again
How to Get All the Sundays in Array of Date iOS
Rotate Image in Share Extension
Handle Multiple File (Image) Uploads to Aws S3 Swift
Hidden Property Cannot Be Changed Within an Animation Block
Getting Uiwebview API Deprecation Message After Adding Paypal Pod in My iOS App