Alexey
Alexey

Reputation: 7247

NSURLSession dataTaskForRequest:completion: unrecognized selector sent to instance

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

Upvotes: 51

Views: 10537

Answers (4)

pierre23
pierre23

Reputation: 3936

In SWIFT 3.0 and up:

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

            //Your code
        }).resume()

Upvotes: 5

Arsen
Arsen

Reputation: 10951

You have to init URLSession with a configuration:

URLSession(configuration: .default)

or use shared session

URLSession.shared

Upvotes: 113

Jay Mehta
Jay Mehta

Reputation: 1791

Do the initialization while declaration :-

var session = URLSession(configuration: .default)

Upvotes: 1

vadian
vadian

Reputation: 285059

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?)

Upvotes: 2

Related Questions