NSURLSession dataTaskForRequest:completion: unreco

2019-04-17 18:26发布

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

4条回答
Rolldiameter
2楼-- · 2019-04-17 18:55

You have to init URLSession with a configuration:

URLSession(configuration: .default)

or use shared session

URLSession.shared
查看更多
乱世女痞
3楼-- · 2019-04-17 19:00

Do the initialization while declaration :-

var session = URLSession(configuration: .default)
查看更多
我只想做你的唯一
4楼-- · 2019-04-17 19:18

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?)
查看更多
Rolldiameter
5楼-- · 2019-04-17 19:19

In SWIFT 3.0 and up:

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

            //Your code
        }).resume()
查看更多
登录 后发表回答