Thom
Thom

Reputation: 153

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 actual Url 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 break point 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?

Upvotes: 0

Views: 624

Answers (2)

picciano
picciano

Reputation: 22701

You are never starting the task. Try this:

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)

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

Upvotes: 0

Khiem Tran
Khiem Tran

Reputation: 6169

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

Upvotes: 6

Related Questions