2017-07-11 1 views
0

私はAPIで新しく、スキポール空港のAPIからデータをインポートしようとしています。最初に私はこのリンクをクエリで試しましたが、次に私は次の結果を得ました。APIのCURLを使用

https://api.schiphol.nl/public-flights/flights?app_id=////APPID////&app_key=////APPKEY////&includedelays=false&page=0&sort=%2Bscheduletime

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() 
} 

誰かが私を助けてくれますか?

答えて

1

URLの代わりにURLRequestを使用し、ヘッダーフィールドを追加します。

これは、cURLの構文のスウィフトと同等です:

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) 
0

あなたは、コールのヘッダーにResourceVersionを設定する必要がAPI文書によります。

次のように動作するはずです:

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()