NSURLSession dataTaskForRequest:completion: unrecognized selector sent to instance

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)