我的应用程序接收位置更新,当它发生时(如果它们相关),我使用完成处理程序异步调用API。当应用程序打开时,只有在之前没有完成请求的情况下(两个请求通常同时进入),完成处理程序才会响应。当我调试时,在所有一切正常工作的前2-3个请求(同时进入)之后,当位置更新通过相关时,将跳过整个完成处理部分代码。
这就是我调用完成处理程序的方式:
if conditions {
let lat = Float(loc.lat)
let long = Float(loc.long)
// calls function using completion handler in order to add new location
BusStations.allBusStations(lat: lat, long: long) { (busStations, error) in
if let error = error {
// got an error in getting the data
print(error)
return
}
guard let busStations = busStations else {
print("error getting all: result is nil")
return
}
if !busStations.stops.isEmpty || self.locations.isEmpty {
// do stuff
}
}
}
这就是我调用API的方式:
static func allBusStations (lat: Float, long: Float, completionHandler: @escaping (BusStations?, Error?) -> Void) {
let endpoint = BusStations.endpointForBusStations(lat: lat, long: long)
guard let url = URL(string: endpoint) else {
print("Error: cannot create URL")
let error = BackendError.urlError(reason: "Could not construct URL")
completionHandler(nil, error)
return
}
let urlRequest = URLRequest(url: url)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
guard let responseData = data else {
print("Error: did not receive data")
completionHandler(nil, error)
return
}
guard error == nil else {
completionHandler(nil, error)
return
}
let decoder = JSONDecoder()
do {
let stations = try decoder.decode(BusStations.self, from: responseData)
completionHandler(stations, nil)
} catch {
print("error trying to convert data to JSON")
print(error)
completionHandler(nil, error)
}
}
task.resume()
}
我做错了什么?任何帮助将不胜感激。
答案 0 :(得分:0)
我会尝试将完成处理程序分派给全局或主队列,以查看它是否被系统推迟在较低级别的队列上执行。