Alex Alex - 5 months ago 128
iOS Question

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

Answer

You have to init NSURLSession with configuration:

NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())