2
votes

I am testing the behavior of URLSession when there isn't an internet connection with this code:

var dataTask: URLSessionDataTask?

    let url = NSURL(string: "https://itunes.apple.com/search?media=music&entity=song&term=test")
    dataTask = defaultSession.dataTask(with: url! as URL) {
        data, response, error in

        if let error = error {
            print(error.localizedDescription)
        } else if let _ = response as? HTTPURLResponse {
            print("ok")
        }
    }
    dataTask?.resume()

I execute this code with my internet connection disabled. In iOS9 the completionBlock gets called immediately and I have this error

Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline."

But, when I execute exactly the same code under iOS10 the completion block gets called after one minute (the timeout) and the error that i have is different

Error Domain=NSURLErrorDomain Code=-1001 "The request timed out."

I need to have the same behavior under iOS9 and iOS10. I am using xCode 8.1 and I am using the simulator to test the app under different iOS versions.

Thanks!

1
Seems to be a problem related to the simulator, because on the device is working correctly. - Juan Pablo Garcia

1 Answers

-4
votes

for check your connection, you can use Reachability class on github

it works like a charm.