等待Swift/SwiftUI功能



我是swift和SwiftUI的新手,我有一个大问题,我希望有人能帮助我。事实上,我有个函数,我使用了对firebase Db的调用,但函数在firebase响应之前结束。那么,有什么办法可以像在swift中等待一样呢?我试着自己找,但我所尝试的一切都不起作用。

我放了一个代码样本,它可能会更清晰。

extension SessionStore {
func checkReferralCode(){
let docRef = db.document(user.referredBy)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let otherUser = self.changeReferralUserInformation(dataDescription: document)
docRef.setData(otherUser)
self.user.moneyBalance = 1
return
} else {
print("No referral Code")
self.firestoreError = "referralCode_unvalid"
self.user.referredBy = ""
return
}
}
}
func doInscriptionInformation()  {
if (self.user.referredBy != "") {
self.checkReferralCode()
if (self.firestoreError == "" ) {
/* it's always go in this way but 1 secs after the firestoreError change */
print("START UPLOAD")
self.determineUploadType()
} else {
return
}
}
}

输出将是:

$> START UPLOAD
$> No referral Code

我使用信号量找到了答案,这里是教程的链接https://medium.com/@roykronenfeld/semaphores-in-swift-e296ea80f860

这里的代码


func checkReferralCode(semaphore: DispatchSemaphore){
let docRef = self.db.document(self.user.referredBy)
semaphore.wait()
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let otherUser = self.changeReferralUserInformation(dataDescription: document)
docRef.setData(otherUser)
self.user.moneyBalance = 1
semaphore.signal()
} else {
self.firestoreError = "referralCode_unvalid"
self.user.referredBy = ""
semaphore.signal()
}
}
}
func doInscriptionInformation()  {
let semaphore = DispatchSemaphore(value: 1)
DispatchQueue.global(qos: .userInteractive).async {
if (self.user.referredBy != "") {
self.checkReferralCode(semaphore: semaphore)
semaphore.wait()
if (self.firestoreError == "" ) {
self.determineUploadType()
}
else {
print("No good referral code")
}
semaphore.signal()
}
}
}

希望能帮助

使docRef成为类的变量,而不是像这样的局部变量:

class WhateverClassNameYouHave: InheritedClass {
let docRef : DocRef (whatever type it is)

func checkCode() {
self.docRef = /* get firebase doc */
/* Call to firebase function */
docRef.getDocument { (document, error) in
/* Do my stuff*/
} else {
/*change variable to error*/
self.firestoreError = "referralCode_unvalid"
}
}
/*But the fonction end before the response of firebase so my self.firestoreError  isn't update */
}

最新更新