使用 NSURLSession 下载 JSON 没有 return 任何数据

Downloading JSON with NSURLSession doesn't return any data

我目前正在尝试从 URL 下载、解析和打印 JSON。 到目前为止,我已经到了这一点:

1) A class (JSONImport.swift),它处理我的导入:

    var data = NSMutableData();
        let url = NSURL(string:"http://headers.jsontest.com");
        var session = NSURLSession.sharedSession();
        var jsonError:NSError?;
        var response : NSURLResponse?;

        func startConnection(){

            let task:NSURLSessionDataTask = session.dataTaskWithURL(url!, completionHandler:apiHandler)
            task.resume();

            self.apiHandler(data,response: response,error: jsonError);

        }

        func apiHandler(data:NSData?, response:NSURLResponse?, error:NSError?)
        {
            do{
                let jsonData : NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary;
                print(jsonData);
            }
            catch{
                print("API error: \(error)");
            }
        }

我的问题是,

中的数据
do{
            let jsonData : NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary;
            print(jsonData);
        }

仍然是空的。 当我调试时,连接成功启动,给定的 url 作为参数。但是我的 jsonData 变量没有被打印出来。相反,catch 块抛出错误,指出我的变量中没有数据:

API error: Error Domain=NSCocoaErrorDomain Code=3840 "No value."

有人可以帮我解决这个问题吗? 我错过了什么?

非常感谢大家!

[从 NSURL 连接切换到 NSURLSession 后编辑]

这里有一个关于如何使用 NSURLSession 的例子,非常方便"completion handler"。

此函数包含网络调用并具有 "completion handler"(数据何时可用的回调):

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

你可以像这样使用它,在一个新函数中,使用 "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)")
        }
    }
}