Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!) } 
like image 842
Alexey Avatar asked Oct 02 '15 11:10

Alexey


2 Answers

You have to init URLSession with a configuration:

URLSession(configuration: .default) 

or use shared session

URLSession.shared 
like image 136
Arsen Avatar answered Sep 21 '22 15:09

Arsen


In SWIFT 3.0 and up:

        URLSession.shared.dataTask(with: url, completionHandler:         {             (data, response, error) in              //Your code         }).resume() 
like image 43
pierre23 Avatar answered Sep 20 '22 15:09

pierre23