DNS failure detection using NSURLSession configuration?

Is it possible to detect DNS lookup errors when used NSURLSessionwith background configuration?

If I use the default configuration and the completion handler, a DNS resolution error is reported in the error parameter. However, if I use the background configuration, an error is never reported and delegate methods are never called.

Apple's documentation for the protocol NSURLSessionTaskDelegatereads:

Server errors are not reported through the error parameter. The only errors your delegate receives through the error parameter are client errors , such as the inability to resolve the host name or connect to the host.

This suggests that I should see a DNS error message. The code below illustrates the behavior. I tested on iOS 8.4 and 9 on both devices and simulators and searched the dev, SO forums and using popular search engines, but came out empty. I am sure that I must skip something very simple.

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, NSURLSessionTaskDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {


        let bgsesh = NSURLSession(configuration: NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("foobarbazqwux"), delegate: self, delegateQueue: nil)
        let dfsesh = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil)

        let url = NSURL(string: "http://foobarbaz.qwzx")!
        let a = dfsesh.downloadTaskWithURL(url) { (url:NSURL?, resp:NSURLResponse?, err:NSError?) -> Void in
            print(err)

            /* 
            Optional(Error Domain=NSURLErrorDomain Code=-1003
            "A server with the specified hostname could not be found." 
            UserInfo=0x146e8050 {
                NSErrorFailingURLStringKey=http://foobarbaz.qwzx/,
                _kCFStreamErrorCodeKey=8,
                NSErrorFailingURLKey=http://foobarbaz.qwzx/, 
                NSLocalizedDescription=A server with the specified hostname could not be found., 
                _kCFStreamErrorDomainKey=12, 
                NSUnderlyingError=0x14693ab0 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1003.)"
            })
            */
        }
        a.resume()

        let b = bgsesh.downloadTaskWithURL(url)
        b.resume()

        return true
    }
    func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
        // never runs, DNS failure is not reported for background config :-(
        print("didCompleteWithError: \(task.taskIdentifier) \(error)")
    }
    // ... other delegate methods ...
}
+4
source share

All Articles