swift - 等待某个任务完全完成后再执行另一个任务

标签 swift firebase asynchronous grand-central-dispatch

我正在尝试从 Firebase 实时数据库检索一些加密消息,解密它们,然后将它们显示在 CollectionView 中。解密过程成功,但我遇到了一个关于多线程的问题:添加到 Messages 数组中的获取的解密消息的顺序是错误的,因此它们没有以正确的顺序显示在 CollectionView 中,即显示消息的顺序每次运行期间 CollectionView 中的内容都会有所不同。我认为发生这个问题是因为每个加密消息完成解密过程所需的时间不同,有些加密消息需要更多时间解密,而有些加密消息先于其他消息完成解密,因此它们添加到 Messages 数组的顺序是不再正确。我期望的工作流程:

  1. 向 Firebase 数据库上的消息节点发出提取请求
  2. 对于每条获取的消息:
    3.1.解密它
    3.2。将其附加到 Messages 数组
    3.3。重新加载 CollectionView 以更新 UI

但我不知道如何使用 GCD 来正确实现这一点,由于并发问题,显示消息的顺序不正确。但是,我找到了一个解决方案,如果我尝试将 sleep(1) 命令放置到我的代码中,代码会正确运行,但由于 sleep 命令而速度太慢。我尝试了很多方法,但似乎都不正确,除了使用 sleep(1) 命令。请帮助我正确地做到这一点,非常感谢!这是我的代码:

func observeMessage(){ 
        self.eThree = VirgilHelper.sharedVirgilHelper.eThreeToUse!

        // Get current user's UID
        guard let uid = FIRAuth.auth()?.currentUser?.uid , let toId = self.user?.id else {
            return;
        }

        let userMessagesRef = FIRDatabase.database().reference().child("user-messages").child(uid).child(toId);
        userMessagesRef.observe(.childAdded, with: { (snapshot) in

            let messageId = snapshot.key;
            let messagesRef = FIRDatabase.database().reference().child("messages").child(messageId);
            // Observe the entire value of that node
            messagesRef.observeSingleEvent(of: .value, with: { (snapshot) in

                if let dictionary = snapshot.value as? [String:AnyObject] {

                //sleep(1) // The working sleep command, but it's too slow

                let message = Message(dictionary: dictionary)
                    if let fromUID = message.fromId, let toUID = message.toId, let cipherText = message.text {

                        self.eThree!.lookupPublicKeys(of: [fromUID], completion: { (lookupResult, error) in
                            if error != nil {
                                print("Error when looking up the Public Key of UID \(fromUID), \(String(describing: error))")
                            }
                            if let lookupResult = lookupResult {
                                message.text = try! self.eThree!.decrypt(text: cipherText, from: lookupResult[fromUID]!)
                                print("text: \(message.text)")

                                // The concurency prolem happens at here
                                self.messages.append(message);

                                // Go back to main thread to update UI
                                DispatchQueue.main.async {
                                    // The concurency prolem happens at here, UI doesn't display with correct order of fetched-decrypted messages
                                    self.collectionView?.reloadData()

                                    let indexPath = IndexPath(item: self.messages.count-1, section: 0)
                                    self.collectionView?.scrollToItem(at: indexPath, at: .bottom, animated: true);
                                }
                            }

                        })
                    }
                }

            }, withCancel: nil)
        }, withCancel: nil)

    }

最佳答案

在 Swift 中,要等待另一个任务完成后再继续其他任务,可以使用 DispatchQueue.group()。

let group = DispatchGroup()

group.enter()
DispatchQueue.main.async {
    print("1")
    group.leave()
}

group.enter()
DispatchQueue.main.async {
    print("2")
    group.leave()
}

group.enter()
DispatchQueue.main.async {
    print("3")
    group.leave()
}

group.notify(queue: .main) {
    print("Done")
}

所以你使用它的方式:

  1. 初始化组
  2. 在开始任务之前输入分组:group.enter()
  3. 在每个任务之后放置:group.leave()
  4. 将闭包传递给 group.notify。当组任务为空时执行。

注意: 多个 .enter() 需要与 .leave() 匹配

关于swift - 等待某个任务完全完成后再执行另一个任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55975373/

相关文章:

node.js - 使用 NodeJs 异步查询 redshift 集群

.net - .NET 中异步操作的线程静态变量

asynchronous - F#如何运行几个异步任务并等待第一个完成的结果?

ios - 如何检测 UICollectionViewCell 的中点何时位于 UICollectionView 的框架之外?

Swift:使用 Firebase 的 UICollectionView 分页

angular - 如何从 Angular 7 中的 Firestore 查询中获取数据的 Observable?

javascript - 将值从 Firebase JS 回调方法 (DAL) 返回到另一个函数( Controller )

ios - 在ios swift中覆盖文本文件

ios - 使用 Swift 包管理器添加依赖项

swift - 关联值符合 CaseIterable、RawRepresentable 的枚举