嗨,我有一个快速的 Web 服务工作者对象,它将完成块传递给调用者视图控制器。代码如下:
func getFlightData(for airportCode: String, minutesBehind:String, minutesAhead:String, completion: (([Flight], NSError) -> Void)?) {
var urlComponents = URLComponents()
urlComponents.scheme = "https"
urlComponents.host = "xxxxxxx.com"
urlComponents.path = "/1/airports/"+airportCode+"/flights/flightInfo"
urlComponents.queryItems = [
URLQueryItem(name: "city", value: airportCode),
URLQueryItem(name: "minutesBehind", value: minutesBehind),
URLQueryItem(name: "minutesAhead", value: minutesAhead)
]
guard let url = urlComponents.url else { fatalError("Could not create URL from components") }
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("xxxxxxxxx", forHTTPHeaderField: "Authorization")
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request) { (responseData, response, responseError) in
DispatchQueue.main.async {
if let error = responseError {
//completion block???
}
else if let jsonData = responseData {
let decoder = JSONDecoder()
do {
let posts = try decoder.decode([Flight].self, from: jsonData)
//completion?(posts, nil) ???? what to pass for Error? Successful call
} catch {
self.showError()
}
}
else {
//completion block???
self.showError()
}
}
}
task.resume()
}
调用成功时,我在完成块错误参数中传递了什么值。我不能通过 nil,因为 swift 不允许我这样做。有人可以建议一种更好的方法来进行此 API 调用吗?如何发送完成块等