Downloading JSON with NSURLSession doesn’t return any data

Here’s an example on how to use NSURLSession with a very convenient “completion handler”.

This function contains the network call and has the “completion handler” (a callback for when the data will be available):

func getDataFrom(urlString: String, completion: (data: NSData)->()) {
    if let url = NSURL(string: urlString) {
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url) { (data, response, error) in
            // print(response)
            if let data = data {
                completion(data: data)
            } else {
                print(error?.localizedDescription)
            }
        }
        task.resume()
    } else {
        // URL is invalid
    }
}

You can use it like this, inside a new function, with a “trailing closure”:

func apiManager() {
    getDataFrom("http://headers.jsontest.com") { (data) in
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data, options: [])
            if let jsonDict = json as? NSDictionary {
                print(jsonDict)
            } else {
                // JSON data wasn't a dictionary
            }
        }
        catch let error as NSError {
            print("API error: \(error.debugDescription)")
        }
    }
}

Leave a Comment