使UI等待方法响应

时间:2019-06-24 19:56:03

标签: swift multithreading grand-central-dispatch

我是一名新的快速开发人员。我正在使用Swift 4.2和Xcode 10.2。

我需要UI等待方法完成,以便可以使用结果显示余额。我正在尝试为此使用dispatchGroup,但是它似乎没有在等待,因为下面的user?.userId的值为nil。这是我的代码:

    // Load the local user data.  Must wait until this is done to continue.
    let dispatchGroup = DispatchGroup()

    dispatchGroup.enter()
    let user = LocalStorageService.loadCurrentUser()
    dispatchGroup.leave()

    // Display the current balance.
    // Get a reference to the Firestore database.
    let db = Firestore.firestore()

    // Make sure we have a userId and then update the balance with a listener that keeps it updated.
    // Only run this part when the dispatchGroup has completed (in this case, the user is loaded).
    dispatchGroup.notify(queue: .main) {
        if let userId = user?.userId {

            db.collection("subs").whereField("ID", isEqualTo: userId)
                .addSnapshotListener { querySnapshot, error in
                    // Make sure we have a document
                    guard let document = querySnapshot?.documents.first else {
                        print("Error fetching document: \(error!)")
                        return
                    }
                    // We have a document and it has data.  Use it.
                    self.balance = document.get("balance") as! Double

                    // Format the balance
                    let currencyFormatter = NumberFormatter()
                    currencyFormatter.numberStyle = .currency
                    let balanceString = currencyFormatter.string(from: self.balance as NSNumber)
                    self.balanceLabel.setTitle(balanceString, for: .normal)
            }
        }
    }

如何让UI等待dispatchGroup.enter()中调用的方法完成?

这是LoadCurrentUser中的内容。...

static func loadCurrentUser() -> User? {

    // Loads the current user in the UserDefaults if there is one

    let defaults = UserDefaults.standard

    let userId = defaults.value(forKey: Constants.LocalStorage.storedUserId) as? String
    let phoneNumber = defaults.value(forKey: Constants.LocalStorage.storedPhoneNumber) as? String
    let subscriberId = defaults.value(forKey: Constants.LocalStorage.storedDocumentId) as? String

    guard userId != nil && phoneNumber != nil && subscriberId != nil else {
        return nil
    }

    // Return the user
    let u = User(userId:userId!, phoneNumber:phoneNumber!, subscriberId: subscriberId)

    return u
}

1 个答案:

答案 0 :(得分:0)

当前,您可以通过在回调函数中设置vars来正确地进行操作,因此不需要var products = [{ name: 'TV LCD', price: 100, stock: 50 }, { name: 'pc', price: 500, stock: 50 }, { name: 'Iphone', price: 1000, stock: 10 }] var valorStock = function(arreglo) { var array = [] for (var i = 0, p; p = arreglo[i]; i++) { var obj = {}; obj[p.name] = p.price * p.stock; array.push(obj); } return array } // or better var valorStock1 = function(arreglo) { return arreglo.map(p => { var obj = {}; obj[p.name] = p.price * p.stock; return obj; }); } console.log(valorStock(products)); console.log(valorStock1(products));,而是可以正确使用它(请注意正确的位置,每行应以1到4的数字表示)

DataFrame