【问题标题】:Downloading JSON with NSURLSession doesn't return any data使用 NSURLSession 下载 JSON 不会返回任何数据
【发布时间】:2016-02-09 10:18:15
【问题描述】:

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

1) 处理我的导入的类 (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 Connection 切换到 NSURLSession 后编辑]

【问题讨论】:

  • 只是一个建议:无论如何不要使用 NSURLConnection,它已被弃用,改用 NSURLSession。
  • 感谢您的提示。还没有意识到这一点。
  • 关于如何在我的代码中使用它有什么建议吗?
  • 此处的示例:stackoverflow.com/a/24041204/2227743 但在 SO 上还有很多其他的。搜索[swift] NSURLSession。
  • 编辑了问题:)

标签: json swift connection


【解决方案1】:

这是一个关于如何使用 NSURLSession 和一个非常方便的“完成处理程序”的示例。

此函数包含网络调用并具有“完成处理程序”(数据可用时的回调):

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

你可以像这样在一个新函数中使用它,带有一个“尾随闭包”:

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

【讨论】:

  • 谢谢!我会尝试一下,并将其与我做错的进行比较:)
  • 花了我比你多一点的时间才弄明白 :D 非常感谢先生! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多