Swift 使用API中的CURL
我是API新手,我正在尝试从史基浦机场的API导入数据。首先,我在查询中尝试了这个链接,但随后得到了以下结果 我想我必须使用旋度来得到一个结果,但我不知道如何在SWIFT 3中做到这一点Swift 使用API中的CURL,swift,rest,nsurlsession,Swift,Rest,Nsurlsession,我是API新手,我正在尝试从史基浦机场的API导入数据。首先,我在查询中尝试了这个链接,但随后得到了以下结果 我想我必须使用旋度来得到一个结果,但我不知道如何在SWIFT 3中做到这一点 CURL: curl -X GET --header "Accept: application/json" --header "ResourceVersion: v3" "https://api.schiphol.nl/public-flights/flights?app_id=////APPID////&a
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()
}
有人能帮我吗?使用
URLRequest
并添加标题字段,而不是简单的URL
这是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)
根据
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()
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()