首页 > 解决方案 > 编写完成处理程序的最佳方法是什么

问题描述

我目前正在我的应用程序中实现应用程序内购买,在恢复购买后,我想调用完成以执行向用户显示警报的操作。我是这样做的,发现一个帖子说它甚至可能不会被执行。我怎样才能正确地构建它。

func restoreIAPPurchases(completion: (() -> Void)) {
    if !self.canMakePayments {
        return
    }
    self.paymentQueue.restoreCompletedTransactions()
    completion()
}

let alertController = UIAlertController.vy_alertControllerWithTitle(nil, message:  "Restore will reprocess your existing subscription. You will not be charged", actionSheet: false)
    alertController.addAction("Ok")
    alertController.addActionWithTitle("Restore", style: .default) {
    IAPService.shared.restoreIAPPurchases {
       UIAlertController.vy_showAlertFrom(self, title: "Restore complete", message: "Successfully restored purchase")
     }
}
     alertController.presentFrom(self)

标签: iosswiftclosurescompletionhandler

解决方案


“我是这样做的,发现一个帖子说它甚至可能不会被执行”

它可能不会被执行,因为您没有在所有路径上调用完成处理程序。

正如 Sh_Khan 在他的回答中提到的那样,您实际上并不需要一个完成处理程序,您需要使用委托方法来通知它何时完成以及它是否成功。但是对特定代码的特殊问题是您没有在 if 语句中调用完成。

if !self.canMakePayments {
    return
}

应该是

guard canMakePayments else {
    completion()
    return
} 

在您拥有的代码中,如果 canMakePayments 为 false,那么您的完成代码将不会执行。


推荐阅读