0

I'm using URLSession with background upload. I set session delegate to self. I get no delegate methods called when I start upload task with no Internet connection. I want to show message and cancel task if there is no Internet connection or it breaks while uploading. How can you do that?

let session = URLSession(configuration: URLSessionConfiguration.background(withIdentifier: "background"), delegate: self, delegateQueue: nil)
let request = ...
let data = ...
let task = session.uploadTask(with: request, fromFile: dataURL)
task.resume()

When I use not background task I can know it from

let task = self.session.dataTask(with: request) { (data, response, error) in

    //if let e = error as NSError?,
    //    e.code == Int(CFNetworkErrors.cfurlErrorNotConnectedToInternet.rawValue) {
    // handle no internet
    //}
}
Maksym Shulha
  • 125
  • 1
  • 1
  • 8
  • 2
    `ReachabilitySwift` is your friend – Neil Galiaskarov Sep 28 '18 at 13:12
  • @NeilGaliaskarov NO! That is so unreliable... Doesn't this throws an error because of a time out? You can anticipate to that and keep retrying every X seconds – J. Doe Sep 28 '18 at 14:29
  • 1
    It will not throw a time-out error, because its scheduled as a background task based on priority, so it can be executed up to one week and will wait for the connectivity all this time. @J.Doe – Neil Galiaskarov Sep 28 '18 at 15:39

1 Answers1

0
let task = self.session.dataTask(with: request) { (data, response, error) in

    //if let e = error as NSError?,
    //    e.code == Int(CFNetworkErrors.cfurlErrorNotConnectedToInternet.rawValue) {
    // handle no internet
    //}
}

Completion block never called in background session(when your app is background). You need use delegates, that called after finish all tasks.

If you don't use delegate. Use Reachability.whenUnreachable block: cancel tasks and show message