我编写了简单的代码来从News API获取JSON数据。我有一个API密钥并按如下方式实现:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let url = URL(string: " https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey=af5f94cdf07e42ee877a3f2c2199d097")
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = [
"user_key": "xxxxxxxxxxxxxxxxxxxxxxxxx"
]
let task = URLSession.shared.dataTask(with: url!) {
(data, response, error) in if error != nil {
print("Error")
}
else {
if let content = data {
do {
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
if let articles = myJson["articles"] as? NSDictionary {
if let titles = articles["title"] {
print(titles)
}
}
}
catch {}
}
}
}
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
然而,有了这个,应用程序崩溃并给出错误:“EXC_BAD_INSTRUCTION(code = EXC_I386_INVOP,subcode = 0x0)” 为什么会出现此错误以及如何解决?
编辑:删除网址中的空格似乎解决了问题,但现在控制台无法打印(标题)(控制台上没有显示任何内容)