使用 NSURLSession 下载 JSON 不会返回任何数据 [英] Downloading JSON with NSURLSession doesn't return any data

查看:17
本文介绍了使用 NSURLSession 下载 JSON 不会返回任何数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently trying to download, parse and print JSON from an URL. So far I got to this point:

1) 处理我的导入的类 (JSONImport.swift):

1) A class (JSONImport.swift), which handles my import:

    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 块会抛出错误,指出我的变量中没有数据:

remains empty. When I debug,the connection starts successfully, with the given url as a parameter. But my jsonData variable doesn't get printed. Instead the catch block throws the error, stating that there is no data in my variable:

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

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

Can someone please help me with this? What am I missing?

提前非常感谢大家!

[从 NSURL Connection 切换到 NSURLSession 后编辑]

推荐答案

这里有一个例子,说明如何通过一个非常方便的完成处理程序"来使用 NSURLSession.

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

这篇关于使用 NSURLSession 下载 JSON 不会返回任何数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆