NSURLSession dataTaskForRequest:completion: unrecognized selector sent to instance
Asked Answered
J

4

51

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!)
}
Joashus answered 2/10, 2015 at 11:8 Comment(1)
Try initializing with configuration. NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())Disjoint
S
113

You have to init URLSession with a configuration:

URLSession(configuration: .default)

or use shared session

URLSession.shared
Smoothbore answered 2/10, 2015 at 11:13 Comment(2)
Thanks It works, I assumed that it have used defaultSessionConfiguration by default if I don't pass anything to the constructorJoashus
For Swift 3 the syntax is now: URLSession(configuration: URLSessionConfiguration.default)Cerebro
S
5

In SWIFT 3.0 and up:

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

            //Your code
        }).resume()
Solid answered 17/10, 2016 at 15:44 Comment(0)
T
2

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?)
Tapster answered 2/10, 2015 at 11:15 Comment(0)
O
1

Do the initialization while declaration :-

var session = URLSession(configuration: .default)
Overprize answered 2/5, 2017 at 14:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.