我是API的新手,我正在尝试从史基浦机场的API导入数据。首先,我在查询中尝试了此链接,但后来得到了以下结果。
result: {code = 406; description = "Can't retrieve version number from accept-header";}
我认为我必须使用CURL来获得结果,但我不知道如何在SWIFT 3中做到这一点。
CURL: curl -X GET --header "Accept: application/json" --header "ResourceVersion: v3" "https://api.schiphol.nl/public-flights/flights?app_id=////APPID////&app_key=////APPKEY////&includedelays=false&page=0&sort=%2Bscheduletime"
我的代码现在看起来像这样:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let url = NSURL(string: "https://api.schiphol.nl/public-flights/flights?app_id=////APPID////&app_key=////APPKEY////&scheduledate=2017-07-11&airline=CND&includelays=false&page=0&sort=%2Bscheduletime")!
let task = URLSession.shared.dataTask(with: url as URL) { (data, response, error) -> Void in
if let urlContent = data {
do{
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)
print(jsonResult)
} catch{
print("failed")
}
}
}
task.resume()
}
有人可以帮帮我吗?
答案 0 :(得分:1)
而不是简单的URL
使用URLRequest
并添加标题字段。
这是与CURL语法相当的Swift:
let url = URL(string: "https://api.schiphol.nl/public-flights/flights?app_id=xxxxxxx&app_key=yyyyyyyyyyyyy5&scheduledate=2017-07-11&airline=CND&includelays=false&page=0&sort=%2Bscheduletime")!
var request = URLRequest(url: url)
request.addValue("v3", forHTTPHeaderField: "ResourceVersion")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) -> Void in ...
我将个人数据设为匿名。
注意:不要在JSONSerialization
中传递任何选项,选项.mutableContainers
在Swift中完全没用。
let jsonResult = try JSONSerialization.jsonObject(with: urlContent)
答案 1 :(得分:0)
根据API
文档,您需要在呼叫的标头中设置ResourceVersion
。
以下内容应该有效:
var req = URLRequest.init(url: URL.init(string: "https://api.schiphol.nl/public-flights/flights?app_id=//APPID//&app_key=//APPKEY//")!)
req.setValue("v3", forHTTPHeaderField: "ResourceVersion")
URLSession.shared.dataTask(with: req) { (data, response, error) in
print(try? JSONSerialization.jsonObject(with: data!, options: .init(rawValue: 4)))
}.resume()