我正在尝试使用 URLSession 使用 stackoverflow api 执行 get 请求,但我不断收到以下错误:
无法读取数据,因为格式不正确。
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
searchBar.sendsWholeSearchString = true
if let url = URL(string: "https://api.stackexchange.com/docs/search#order=desc&sort=activity&intitle=swift&filter=default&site=stackoverflow") {
var request = URLRequest(url: url)
request.httpMethod = "GET"
let dataTask = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
//handle response here
if let error = error {
print("Fuck! \(error.localizedDescription)")
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
print(json)
} catch {
print(error.localizedDescription)
}
}
dataTask.resume()
}
}
我已经将网址设置为从搜索中获取 swift
结果,因此网址为“https://api.stackexchange.com/docs/search#order=desc&sort=activity&intitle=swift&filter=default&site=stackoverflow ”
我还读到数据通常是 gzip 格式,但发现显然 URLSession 自动处理它..
对我哪里出错有什么建议吗?
最佳答案
我应该使用的正确网址是 https://api.stackexchange.com/2.2/search?order=desc&sort=activity&intitle=swift&site=stackoverflow
而不是
关于swift - 无法将 API 请求中的数据转换为 JSON - stackoverflow api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58705625/