ios - 为什么这段代码会按这个顺序执行?寻找流程的解释

标签 ios swift

在下面的代码中,我希望从数据库中提取一些属性 - 属于特定 community 成员的 id。

我进行了另一个 API 调用以获取这些社区成员的姓名。

import UIKit

class ShowCommunityViewController: UIViewController {
    @IBOutlet weak var communityName: UILabel!
    var communityIsCalled: String?
    var comIds =  [String]()
    var communityId: Int?
    var communityPlayers =  [String]()
    var communityPlayerIds =  [String]()


    override func viewDidAppear(_ animated: Bool) {
        let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/specificCommunity.php?");
        var request = URLRequest(url:myUrl!);
        request.httpMethod = "POST";
        let postString = "id=\(comIds[communityId!])";
      //  print (postString)
        request.httpBody = postString.data(using: String.Encoding.utf8);

        let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in

            DispatchQueue.main.async
                {
                    if error != nil {
                        print("error=\(error)")
                        return
                    }

                    do{
                        let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
                     // print (json)
                       if let arr = json?["players"] as? [[String:String]] {
                            let players = arr.flatMap { $0["player_id"]!
                               // print(arr)
                          }
                        print ("one ",players)
                        self.communityPlayerIds = players
                        }

                    } catch{
                        print(error)
                    }
            }
        }
        task.resume()

        let myUrlTwo = URL(string: "http://www.quasisquest.uk/KeepScore/getPlayers.php?");
        var requestTwo = URLRequest(url:myUrlTwo!);
        requestTwo.httpMethod = "POST";
        let postStringTwo = "player_ids=\(self.communityPlayerIds)";
        print ("two ",postStringTwo)
        requestTwo.httpBody = postStringTwo.data(using: String.Encoding.utf8);

        let taskTwo = URLSession.shared.dataTask(with: requestTwo) { (data: Data?, response: URLResponse?, error: Error?) in

            DispatchQueue.main.async
                {

                    if error != nil {
                        print("error=\(error)")
                        return
                    }

                    do{
                        let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
                        // print (json)
                        if let arr = json?["player_names"] as? [[String:String]] {
                            let playerNames = arr.flatMap { $0["user_name"]!
                                // print(arr)

                            }
                            print ("three ", playerNames)
                        }



                    } catch{
                        print(error)
                    }
            }
        }
        taskTwo.resume()


    }


    override func viewDidLoad() {
        super.viewDidLoad()

        communityName.text = communityIsCalled

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

如果您注意打印调试命令的顺序一、二、三

它们实际上按照二、一、三的顺序执行。

因为 twoone 之前执行,我的 Post String 没有查找名称所需的 player_ids

有人可以向我解释一下流程吗?

最佳答案

首先,让我们去掉所有内容,只留下代码中的 3 个 print 语句

let task = URLSession.shared.dataTask(with: request) {
    print("one")
}    
task.resume()

print("two")
let taskTwo = URLSession.shared.dataTask(with: requestTwo) {
    print("three")
}
taskTwo.resume()

URLSession 任务异步执行。当您调用 task.resume() 时,它会将指令发送到另一个线程并立即跳转到下一行,而无需等待 task 完成。与 CPU 的速度相比,网络请求非常慢,因此它几乎总是在 one 之前打印 two

onethree的顺序是不确定的,取决于服务器响应哪个更快。

关于ios - 为什么这段代码会按这个顺序执行?寻找流程的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40243584/

相关文章:

php - 将数据从 IOS 应用程序发布到 PHP Web 服务(托管 GODADDY)

ios - SwiftUI使用Charts创建RadarChart并希望实时更新RadarChartDataEntry

python - Swift 中的十六进制/二进制字符串转换

ios - 透明 查看颜色从黑色到其他颜色?

json - Swift 解析 json 读为 nil

ios - Swift PhysicsBody 不受 Impulse 影响

ios - 更新陀螺仪相对于预定义方向的旋转数据?

ios - 无法通过主类的选择器调用类别方法

ios - UIProgressView 设置为图像? UIprogressView 整个contentView,向下?

IOS Swift 解包 NSData 崩溃