1

Swift 3 on Xcode 8β3.

Any ideas why the code below is throwing the error (further) below, particularly given that I am using URLSession not NSURLSession?

CODE

public func updateCurrentConditions() {

    let session = URLSession()
    let url     = URL(string: "http://api.wunderground.com/api/\(key)/conditions/51.32,-1.0.json")!
    let loadDataTask = session.dataTask(with: url, completionHandler: self.dataHandler) 
    loadDataTask.resume()
}

private func dataHandler(data: Data?, response: URLResponse?, error: NSError?) -> Void {
    print("dataHandler executed.")
}

ERROR

failed: caught "NSInvalidArgumentException", "-[NSURLSession dataTaskForRequest:completion:]: unrecognized selector sent to instance 0x7fac89569f00"

Vince O'Sullivan
  • 2,611
  • 32
  • 45

1 Answers1

1

Have you tried using shared URLSession?

let session = URLSession.shared

The default initializer of URLSession is undefined, so it may be creating something weird...

OOPer
  • 47,149
  • 6
  • 107
  • 142
  • Ah, I had tried a couple of similar variants but as instance rather than static functions. That works. Well, it compiles and runs anyway. Still not calling the completion handle though. :( – Vince O'Sullivan Jul 24 '16 at 13:00
  • @VinceO'Sullivan, I believe your code (with `shared` fixed) should work. (Tested in a sample project with using another URL.) Check your URL, key, ATS settings... Hope you can solve those issues soon. – OOPer Jul 24 '16 at 13:16
  • Interesting. Works fine when embedded in a (single view) application but appears not to call the completion handler when embedded in a Cocoa Touch framework. – Vince O'Sullivan Jul 24 '16 at 14:53
  • @VinceO'Sullivan, really interesting. If you can create a simplified example which can reproduce your issue, many readers would take their time to solve the issue. Simplifying would also help you solve your issue yourself. – OOPer Jul 24 '16 at 15:03
  • it doesn't answer the question - `URLSession` has initializers and they should work but it seems you need to customize additionally some params which are obligatory but apple doesn't mention it – Vyachaslav Gerchicov Jul 22 '20 at 06:59