无法弄清楚为什么这不起作用... 当我运行它时,我在控制台中出现此错误:
[CONNECTION] OK, data correctly downloaded
[ERROR] An error has happened with parsing of json data
nil
可能是我在 salvaJson()
函数中传递的链接中的 JSON 格式。
这是 View Controller :
//MARK:proprietà
@IBOutlet weak var meteoLabel: UILabel!
@IBOutlet weak var descrizioneLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let data = salvaJson()
let json = json_parseData(data!)
print(json)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func salvaJson()->NSData?{
guard let url = NSURL(string: "http://www.medialweb.it/corsi_ok.json") else {
return nil
}
guard let data = NSData(contentsOfURL: url) else {
print("[ERROR] There is an unspecified error with the connection")
return nil
}
print("[CONNECTION] OK, data correctly downloaded")
return data
}
// funzione per la generazione del json a partire da un NSData
func json_parseData(data: NSData) -> NSDictionary? {
do {
let json: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
print("[JSON] OK!")
return (json as? NSDictionary)
} catch _ {
print("[ERROR] An error has happened with parsing of json data")
return nil
}
}
我删除了 JSON 顶部的注释。 json_parseData()
现在打印:[JSON] OK!但我仍然有 nil
而不是 printend json
最佳答案
问题出在你的 JSON 上,因为 json 结果必须以数组开头
我测试了你的代码,它是工作代码:
guard let url = NSURL(string: "http://pokeapi.co/api/v2/pokemon/1/") else {
return nil
}
Pokemon Webapi和 test your json format
更新:
how can i print the error?
do {
let json: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
print("[JSON] OK!")
return (json as? NSDictionary)
} catch {
//print("[ERROR] An error has happened with parsing of json data")
print("\(error)")
return nil
}
关于ios - 使用 swift 下载并解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39484705/