Я пытаюсь получить данные с моего узла, отправляя запросы несколько раз (чтобы определить расстояние, на которое машина проезжает). Однако кажется, что выполнение не происходит в правильном порядке. Я считаю, что это связано с тем, что запросы не обрабатываются синхронно.
Я рассмотрел другие вопросы, но, похоже, они не подходят к моей ситуации из-за вложенных запросов.
var d1: Double!
вар d2: двойной!
вар d3: двойной!
var d4: Double!
var speed: Double!
var speed1: Double!
@objc func getSpeed() {
Alamofire.request("\(Constants.appServer)/speed", method: .get).responseJSON { (response) in
if let result = response.result.value as! [String:Any]? {
if let response = result["data"] as! [String: Any]?
{
self.d1 = response["distance"] as? Double
print("First distance is \(self.d1) KM")
//Delay for 5 secods
sleep(5)
//Make the call again.
Alamofire.request("\(Constants.appServer)/speed", method: .get).responseJSON(completionHandler: { (response) in
if let result = response.result.value as! [String: Any]? {
if let response = result["data"] as! [String:Any]?
{
self.d2 = response["distance"] as? Double
print("The second distance is \((self.d2)!)")
let distance = self.d2 - self.d1
print("The total distance for the first part is \(distance)")
self.speed = (distance / 5) * 1000
print("\((self.speed)!) is the speed (m/s) for the first part")
}
}
})
}
}
}
sleep(30)
Alamofire.request("\(Constants.appServer)/speed", method: .get).responseJSON { (response) in
if let result = response.result.value as! [String:Any]? {
if let response = result["data"] as! [String: Any]?
{
self.d3 = response["distance"] as? Double
print("The third distance is \((self.d3)!)")
//Delay for 5 secods
sleep(5)
//Make the call again.
Alamofire.request("\(Constants.appServer)/speed", method: .get).responseJSON(completionHandler: { (response) in
if let result = response.result.value as! [String: Any]? {
if let response = result["data"] as! [String:Any]?
{
self.d4 = response["distance"] as? Double
print("The fourth distance is \((self.d4)!)")
let distance = self.d4 - self.d3
print("The total distance for the second part is \(distance)")
self.speed = (distance / 5) * 1000
print("\((self.speed)!) is the speed (m/s) for the second part")
}
}})
}
}
}
if speed1 == 0 && speed > 90 {
//Wait 5 minutes to see if the car moves
sleep(30)
if speed1 == 0 {
//Send SMS
Alamofire.request("\(Constants.appServer)/message?long=longitude&lat=lat", method: .get).responseJSON { _ in}
}
}else {
print("There is no issue")
}
}
Я запускаю приведенную ниже функцию каждые 5 минут или около того в моем приложении applelegate,