NSURLSession dataTaskForRequest:completion: unrecognized selector sent to instance

若如初见. 提交于 2019-12-22 01:46:50

问题


When trying to create my own session object NSURLSession() and request an url I get an unrecognized selector exception but when I use the shared session NSURLSession.sharedSession() everything works fine. How come?

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!)
}

回答1:


You have to init URLSession with a configuration:

URLSession(configuration: .default)

or use shared session

URLSession.shared



回答2:


In SWIFT 3.0 and up:

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

            //Your code
        }).resume()



回答3:


Aside from the shared session NSURLSession must be initialized with one of these two methods

init(configuration configuration: NSURLSessionConfiguration)


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



回答4:


Do the initialization while declaration :-

var session = URLSession(configuration: .default)


来源:https://stackoverflow.com/questions/32905874/nsurlsession-datataskforrequestcompletion-unrecognized-selector-sent-to-instan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!