作为我正在创建的应用程序的一部分,我实现了运行跟踪功能。我有大部分代码,但我有一段代码几乎执行得太快,我需要在下一段代码执行之前从 newRun.php 脚本返回响应,这是因为它返回了一个 ID,我需要执行下一段代码。
@IBAction func stopRun(_ sender: Any)
{
startButton.isHidden=false
stopButton.isHidden=true
saveRun()
}
上面是运行 saveRun 的代码部分。单击此按钮,我希望它在“run_history”表中创建新记录。仅当此操作完成后,我才希望它使用 newRun.php
脚本返回的 run_id 创建新记录,其中将包括运行的所有经度和纬度。
private func saveRun()
{
首先执行。
let request = NSMutableURLRequest(url: NSURL(string: "../newRun.php")! as URL)
request.httpMethod = "POST"
let postString = "id=\(MainMenuViewController.myVariables.user_id)"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest)
{
data, response, error in
if error != nil
{
print("error=\(String(describing: error))")
return
}
print("response = \(String(describing: response))")
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
MainMenuViewController.myVariables.new_run_id = responseString! as String
print ("Run ID =\(MainMenuViewController.myVariables.new_run_id))")
}
task.resume()
其次执行。
for location in self.locationList
{
var timestamp = location.timestamp
var latitude:String = String(format:"%f", location.coordinate.latitude)
var longitude:String = String(format:"%f", location.coordinate.longitude)
print("Timestamp is \(timestamp)")
print("latitude is \(latitude)")
print("longitude is \(longitude)")
let requestGps = NSMutableURLRequest(url: NSURL(string: "../newRunGps.php")! as URL)
requestGps.httpMethod = "POST"
let postStringGps = "id=\(MainMenuViewController.myVariables.new_run_id)&lng=\(longitude)&lat=\(latitude)&time=\(timestamp)"
requestGps.httpBody = postStringGps.data(using: String.Encoding.utf8)
let taskGps = URLSession.shared.dataTask(with: requestGps as URLRequest)
{
dataGps, responseGps, errorGps in
if errorGps != nil
{
print("error=\(String(describing: errorGps))")
return
}
print("response = \(String(describing: responseGps))")
let responseStringGps = NSString(data: dataGps!, encoding: String.Encoding.utf8.rawValue)
print ("responseString =\(responseStringGps!))")
}
taskGps.resume()
}
}
我看到提到了 DispatchQueue 和 DispatchGroup,但我不确定如果有人可以帮助我解决这个问题,我将如何在我的代码中使用它们?
最佳答案
你可以尝试这样的事情:
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4), execute: {
for vc in (self.navigationController?.viewControllers ?? []) {
if vc is DashboardViewController {
self.navigationController?.popToViewController(vc, animated: true)
break
}
}
})
关于ios - 依次执行一段代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48905055/