7
votes

When I set up NSURLSession/Alamofire.Manager with a background session configuration, if there is no internet connection, I'm expecting to receive the usual NSError "Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline.".

This happened regularly if I'm not using a background configuration, but if I do such configuration my callback/delegate method will never be called. It will eventually be called when I activate the wifi again.

I'd prefer to receive an error straight away. Am I missing something?

2

2 Answers

4
votes

The reason that why the network failure in background session task does not return any error is:

In general an NSURLSession background session does not fail a task if something goes wrong on the wire. Rather, it continues looking for a good time to run the request and retries at that time. This continues until the resource timeout expires (that is, the value in the timeoutIntervalForResource property in the NSURLSessionConfiguration object you use to create the session). The current default for that value is one week!

I found the above answer at developer forum.

More details which might help in the background session:

Another benefit is that in a background session, we monitor the network and power environment for you. This means that we cover things like network reachability and connectivity for you, so you don't have to use the reachability APIs at all. We won't attempt to establish a connection until we know that the server is reachable. And similarly, if the user is performing a download and steps out of Wi-Fi, normally that task would then fail with a transmission error. But, in a background session, we'll actually recover from that automatically and retry it and resume where we left off if the download is resumable. And you won't hear about that error.

Source: WWDC 2014

2
votes

The API doesn't tell you that the network is not present, because that would be an error, indicating that the connection will never finish. In reality, it will, assuming the network eventually comes back.

If you need to receive the error for some reason, don't use a background session.

Alternatively, if you just want to know whether the network is up or not for some sort of UI hint, use the reachability API. With that said, don't refuse to start the request based on failed reachability, because reachability lies.