user3120706 user3120706 - 2 months ago 26
Swift Question

Why doesn't NSURLSession.dataTaskWithURL() call my completion handler?

I'm trying to load a JSON file from a web server. Here's how I kick off the request:

let url:NSURL? = NSURL(string: lookupUrlFragment + query)

// Check if an actual url object was created
if let actualUrl = url {

// Create a default NSURLSessionConfiguration
let sessionConfig:NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()

// Create a default session
let session:NSURLSession = NSURLSession(configuration: sessionConfig)

session.dataTaskWithURL(actualUrl, completionHandler: {
(data:NSData?, response:NSURLResponse?, error:NSError?) in
NSLog("Got data = \(data)")
NSLog("Got response = \(response)")
NSLog("Got error = \(error)")
self.searchResults = data
self.delegate?.searchResultsAreReady()
})
}


I've stepped through this code with the debugger. When it gets to the invocation of dataTaskWithURL() the value of actualUrl is correct. If I hit it from a web browser, I get the JSON file. But the completion handler never gets called. It never stops at a breakpoint I set in the completion handler, and no output appears in the debugger log.

I've tried this with the completion handler in a separate function instead of a closure, but the behavior is the same.

Can anyone tell me why my completion handler isn't getting called?

Answer

You forgot to call resume().

let session:NSURLSession = NSURLSession(configuration: sessionConfig)

let task = session.dataTaskWithURL(actualUrl, completionHandler: {
    (data:NSData?, response:NSURLResponse?, error:NSError?) in
    NSLog("Got data = \(data)")
    NSLog("Got response = \(response)")
    NSLog("Got error = \(error)")
    self.searchResults = data
    self.delegate?.searchResultsAreReady()
})
task.resume() // you miss this