我希望根据异步逻辑显示警报。
这是我的代码:

@IBAction func AddToFavoriteButton(_ sender: Any)
    {
        IsItemInFavoritesAsync(productId: productToDisplay.UniqueID())
        {
            success in

            // Product exists in favorite tree
            Constants.showAlert(title: "Item in Tree", message: "Yes it is", timeShowing: 1, callingUIViewController: self)
        }
        // Product doesn't exist in favorite tree
        Constants.showAlert(title: "Item NOT in Tree", message: "Isn't", timeShowing: 1, callingUIViewController: self)
        Product.RegisterProductOnDatabaseAsFavorite(prodToRegister: productToDisplay, productType: productType)
    }

    private func IsItemInFavoritesAsync(productId: String, completionHandler: @escaping (Bool) -> ())
    {
        let favoriteTree = productType == Constants.PRODUCT_TYPE_SALE ? Constants.FAVORITE_TREE_SALE : Constants.FAVORITE_TREE_PURCHASE
        Constants.refs.databaseRoot.child(favoriteTree).child((Constants.refs.currentUserInformation!.uid)).observeSingleEvent(of: .value, with: {(DataSnapshot) in

            return DataSnapshot.hasChild(self.productToDisplay.UniqueID()) ? completionHandler(true) : completionHandler(false)

        })

    }

此代码段的作用是:
检查产品是否已保存到收藏夹
如果有,显示弹出窗口
如果没有,则显示弹出窗口B
我关注了StackOverflow上的另一篇文章,它指出了我应该如何调用异步函数。(Can Swift return value from an async Void-returning block?
实际发生的情况是,只有popup B显示(在IsItemInFavoritesAsync闭包之外的那一个)。我的错是什么?
我猜IsItemInFavoritesAsync在结束时进入闭包,函数IsItemInFavoritesAsync继续到“Product not in tree”部分。
注意:函数IsItemInFavoritesAsync从Firebase读取。
我该怎么解决?

最佳答案

两个操作(正结果和负结果)都需要在完成处理程序中。
所以像这样:

IsItemInFavoritesAsync(productId: productToDisplay.UniqueID()) { success in
    if success {
      // Product exists in favorite tree
      Constants.showAlert(title: "Item in Tree", message: "Yes it is", timeShowing: 1, callingUIViewController: self)
    }
    else {
      // Product doesn't exist in favorite tree
      Constants.showAlert(title: "Item NOT in Tree", message: "Isn't", timeShowing: 1, callingUIViewController: self)
      Product.RegisterProductOnDatabaseAsFavorite(prodToRegister: productToDisplay, productType: productType)
    }
}

08-05 21:26
查看更多