NSURLSession dataTaskForRequest:completion: 无法识别的选择器发送到实例

NSURLSession dataTaskForRequest:completion: unrecognized selector sent to instance

当我尝试创建我自己的会话对象 NSURLSession() 并请求一个 url 时,我得到一个无法识别的选择器异常,但是当我使用共享会话时 NSURLSession.sharedSession() 一切正常。怎么会?

var url = NSURL(string: "http:/www.google.com")
if url != nil {
    //throws unrecognized selector when dataTaskWithURL is called
    let session=NSURLSession()
    session.dataTaskWithURL(url!)

   //works
    let sharedSession=NSURLSession.sharedSession()
    sharedSession.dataTaskWithURL(url!)
}

您必须 init URLSession 配置:

URLSession(configuration: .default)

或使用共享会话

URLSession.shared

除了共享会话 NSURLSession 必须使用这两种方法之一进行初始化

init(configuration configuration: NSURLSessionConfiguration)


init(configuration configuration: NSURLSessionConfiguration,
               delegate delegate: NSURLSessionDelegate?,
             delegateQueue queue: NSOperationQueue?)

在 SWIFT 3.0 及更高版本中:

        URLSession.shared.dataTask(with: url, completionHandler:
        {
            (data, response, error) in

            //Your code
        }).resume()

在声明时进行初始化:-

var session = URLSession(configuration: .default)