NSURLSession dataTaskForRequest:completion: unrecognized selector sent to instance

IosSwiftNsurlsessionUnrecognized Selector

Ios Problem Overview


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

Ios Solutions


Solution 1 - Ios

You have to init URLSession with a configuration:

URLSession(configuration: .default)

or use shared session

URLSession.shared

Solution 2 - Ios

In SWIFT 3.0 and up:

        URLSession.shared.dataTask(with: url, completionHandler:
        {
            (data, response, error) in
            
            //Your code
        }).resume()

Solution 3 - Ios

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

Solution 4 - Ios

Do the initialization while declaration :-

var session = URLSession(configuration: .default)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexeyView Question on Stackoverflow
Solution 1 - IosArsenView Answer on Stackoverflow
Solution 2 - Iospierre23View Answer on Stackoverflow
Solution 3 - IosvadianView Answer on Stackoverflow
Solution 4 - IosJay MehtaView Answer on Stackoverflow