【发布时间】: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