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

  • UITextField format in xx-xx-xxx
  • IOS: add a parameter to @selector
  • How to make an universal iOS library for both Objective-C and Swift?
  • Swift, Custom UIButton does not work when click
  • The identity certificate for com.xyz.profile.mdm could not be found?
  • UITextField how to disable the paste?
  • 4 Solutions Collect From Internet About “NSURLSession dataTaskForRequest:completion: unrecognized selector sent to instance”

    You have to init URLSession with a configuration:

    URLSession(configuration: .default)
    

    or use shared session

    URLSession.shared
    

    In SWIFT 3.0:

            let task = URLSession.shared.dataTask(with: url)
            task.resume()
    

    or

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

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

    Do the initialization while declaration :-

    var session = URLSession(configuration: .default)