私はSwift 3にアップデートしており、Alamofireと.get要求に問題があります。以下のコードを使用して、SkyScannerのAPIから航空データを取得するための.getリクエストを作成しています。何らかの理由で、最終的な.get要求からのJSON戻り値は、常に部分的に空の値を返します。アップデートが完了し、いくつかの要素に正しいデータが含まれているという正常なメッセージが表示されますが、旅程情報や運送業者情報のようなものは常に空です。AlamofireとSkyScannerを使用してSwift 3にアップデートするときに部分的に空の応答
レスポンスのタイプ(JSON、String、Dataなど)を変更しようとしましたが、それは問題を解決していないようです。このコードはSwift 2で正常に機能しました。その最新のアップデートではすべてが壊れました。部分的に空のJSONレスポンスを引き起こす可能性のあるアイデアはありますか?
import UIKit
import SwiftyJSON
import Alamofire
class ViewController: UIViewController {
var key = "prtl6749387986743898559646983194"
override func viewDidLoad() {
super.viewDidLoad()
getFlights()
}
func getSessionKey(destination: String, outboundDate: String, inboundDate: String, adults: Int, complete: @escaping(_ key: String?, _ error: NSError?) -> Void) {
// Use the mandatory headers listed on the SkyScanner api page http://business.skyscanner.net/portal/en-GB/Documentation/FlightsLivePricingList
let headers: HTTPHeaders = [
"Content-Type":"application/x-www-form-urlencoded",
"Accept":"application/json"
]
let parameters: Parameters = [
"apiKey":key,
"country":"US",
"currency":"USD",
"locationSchema":"iata",
"locale":"EN",
"originplace":"DUB",
"destinationplace":"LON",
"outbounddate":"2017-03-12",
"inbounddate":"2017-03-20",
"adults":1,
"groupPricing":true
]
// First get the session URL key so we can being the poll
let sessionURL = "http://partners.api.skyscanner.net/apiservices/pricing/v1.0"
let sessionPost = Alamofire.request(sessionURL, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: headers)
sessionPost.responseString { (sessionResponse) in
switch sessionResponse.result {
case .success:
if let responseHeader = sessionResponse.response?.allHeaderFields {
// Get the session poll URL from the location header
let locationHeader = responseHeader["Location"] as? String
if let range = locationHeader?.range(of: "v1.0/") {
let sessionKey = locationHeader?.substring(from: range.upperBound)
complete(sessionKey, nil)
}
}
case .failure(let error):
complete(nil, error as NSError?)
}
}
}
func poll(sessionKey: String, complete: @escaping(_ data: JSON?, _ error: NSError?) -> Void) {
// Take the new found session key and plug it into the poll func
let pollingParameters: Parameters = [
"sortype":"price",
"sortorder":"asc",
"includeQuery": false,
"stops": 2,
"includeCurrencyLookup": false,
"includeBookingDetailsLink": true
]
let headers: HTTPHeaders = [
"Content-Type":"application/x-www-form-urlencoded",
"Accept":"application/json"
]
// **PROBLEM HERE AS THE RETURNED VALUE ALWAYS CONTAINS SOME EMPTY ELEMENTS FOR AN UNDETERMINED REASON**
let pollURL = "http://partners.api.skyscanner.net/apiservices/pricing/v1.0/\(sessionKey)?apiKey=\(key)"
let sessionPoll = Alamofire.request(pollURL, method: .get, parameters: pollingParameters, encoding: URLEncoding.default, headers: headers)
sessionPoll.responseJSON(queue: DispatchQueue.global() ,completionHandler: { (response) in
print(response.response?.statusCode ?? "There is no response")
switch response.result {
case .success:
if let value = response.result.value {
//print("RawValue: \(value)")
complete(JSON(value), nil)
}
case .failure(let error):
complete(nil, error as NSError?)
}
})
}
func beginPolling(sessionKey: String, complete: @escaping (_ itineraries: [String:[[String:JSON]]]?, _ error: NSError?) -> Void) {
self.poll(sessionKey: sessionKey) { (data, error) in
if error == nil {
if data?["Status"].stringValue == "UpdatesPending"{
let when = DispatchTime.now() + 1
DispatchQueue.global().asyncAfter(deadline: when, execute: {
print("Updates Pending")
self.beginPolling(sessionKey: sessionKey, complete: { (trips, error) in
complete(trips, error)
})
})
}else if data?["Status"].stringValue == "UpdatesComplete" {
print("Updates Complete: \(data)")
}else {
// There is no Status and we've probably errored out somewhere
}
}else{
// Error
}
}
}
func getFlights() {
getSessionKey(destination: "LON", outboundDate: "2017-03-12", inboundDate: "2017-03-20", adults: 1) { (sessionKey, error) in
if error == nil{
let when = DispatchTime.now() + 1
DispatchQueue.global().asyncAfter(deadline: when, execute: {
self.beginPolling(sessionKey: sessionKey!, complete: { (trips, error) in
if error == nil {
// Take the valid data and pass it on to the next viewcontroller
}else{
// Error
}
})
})
}else {
print("There has been an Error getting the session key")
}
}
}
}