我正在实现In App purchases
,效果很好。我正在实现 Auto-Renewable
和 Non-renewable
订阅。我可以确定任一订阅何时处于事件状态以及何时过期。我可以根据订阅状态更新用户配置文件用户界面,但只能在一次检查一个时执行。
如果我在 View 即将出现时调用两个函数
。用户界面变得困惑,无法显示正确的状态。我已经调试并看到,如果第一个检查一个订阅,更新它的状态,当我移出 view
并返回时,它会检查另一个返回到默认状态,即 standard account
因为 Auto-renewable
已过期。有没有一种方法可以让我同时运行这两个功能并同时使用它们来更新我的用户界面。下面是我的代码。
var isUserActive: Bool?
var user: User {
return AppDelegate.shared.user
}
func setUserAccountType() {
if self.isUserActive == nil {
self.userAccountType.text = ""
self.userGoGold.isHidden = true
} else {
if self.isUserActive! {
self.userAccountType.text = "Gold Account"
} else {
self.userAccountType.text = "Standard Account"
self.userGoGold.isHidden = false
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.setUserAccountType()
IAPManager.shared.getProducts()
}
override func viewWillAppear(_ pAnimated: Bool) {
super.viewWillAppear(pAnimated)
self.checkForAutoRenewableSubscription()
self.checkForNonRenewableSubscription()
}
func setUpUserAccountStatus(_ pIsActive: Bool) {
DispatchQueue.main.async {
self.isUserActive = pIsActive
self.setUserAccountType()
self.reloadRowForIdentifier(.billing)
self.activityIndicator.hidesWhenStopped = true
self.activityIndicator.stopAnimating()
}
}
func checkForAutoRenewableSubscription() {
self.activityIndicator.startAnimating()
self.user.checkIfSubscriptionIsActive { (pIsActive) in
self.setUpUserAccountStatus(pIsActive)
}
}
func checkForNonRenewableSubscription() {
self.activityIndicator.startAnimating()
self.user.checkifNonRenewableSubscriptionIsActive { (pSubscribed) in
self.setUpUserAccountStatus(pSubscribed)
}
}
最佳答案
您需要使用 DispatchGroup
并在其内部通知部分执行您需要的操作
let dispatchGroup = DispatchGroup()
var inpIsActive = false
var inpSubscribed = false
func checkForAutoRenewableSubscription() {
dispatchGroup.enter()
self.activityIndicator.startAnimating()
self.user.checkIfSubscriptionIsActive { (pIsActive) in
self.inpIsActive = pIsActive
self.dispatchGroup.leave()
}
}
func checkForNonRenewableSubscription() {
dispatchGroup.enter()
self.activityIndicator.startAnimating()
self.user.checkifNonRenewableSubscriptionIsActive { (pSubscribed) in
self.inpSubscribed = pSubscribed
self.dispatchGroup.leave()
}
}
在viewDidLoad
checkForAutoRenewableSubscription()
checkForNonRenewableSubscription()
dispatchGroup.notify(queue: .main) {
self.setUpUserAccountStatus()
}
关于ios - 更新UI时如何同时执行2个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55300999/