使用NSURLSession后台配置检测DNS失败?

问题描述 投票:4回答:1

[在后台配置中使用NSURLSession时是否可以检测DNS查找失败?

如果使用默认配置和完成处理程序,则会在error参数中报告DNS解析失败。但是,如果我使用后台配置,则永远不会报告失败,也永远不会调用委托方法。

[NSURLSessionTaskDelegate协议的Apple文档说:

服务器错误不会通过error参数报告。唯一的您的代表通过error参数收到的错误是客户端错误,例如无法解析主机名或连接到主机。

这建议我应该在那里看到DNS失败消息。下面的代码说明了这种行为。我已经在iOS 8.4和9上在设备和模拟器上进行了测试,并使用流行的搜索引擎搜索了开发论坛,但结果空白。我确定我一定会错过一些非常简单的内容。

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 ...
}
ios swift ios8 nsurlsession ios9
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.