你问:
它指出我们应该在 AppDelegate 文件的didFinishLaunchingWithOptions 中添加事务观察器。并且我们应该删除AppDelegate 的applicationWillTerminate 中的事务观察器。
这与我读过的许多教程不符...
不,以这种方式添加它没有任何问题。正如技术说明所说,“在启动时添加应用程序的观察者可确保它在应用程序的所有启动期间持续存在,从而允许您的应用程序接收所有支付队列通知。”
如果您有一些参考建议反对这种做法,请编辑您的问题并与我们分享具体参考,我们可以对该链接进行具体评论。
在评论中,你后来问:
我还必须在AppDelegate 中包含所有相关的委托方法吗?
有几个选项。例如,您可以为此实例化一个专用对象。因此:
let paymentTransactionObserver = PaymentTransactionObserver()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
SKPaymentQueue.default().add(paymentTransactionObserver)
return true
}
func applicationWillTerminate(_ application: UIApplication) {
SKPaymentQueue.default().remove(paymentTransactionObserver)
}
地点:
class PaymentTransactionObserver: NSObject, SKPaymentTransactionObserver {
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { ... }
func paymentQueue(_ queue: SKPaymentQueue, removedTransactions transactions: [SKPaymentTransaction]) { ... }
func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) { ... }
func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) { ... }
func paymentQueue(_ queue: SKPaymentQueue, updatedDownloads downloads: [SKDownload]) { ... }
}
或者,您也可以将其直接添加到您的AppDelegate(如Setting Up the Transaction Observer for the Payment Queue 中所述)。但如果您这样做,您可能希望add protocol conformance with an extension 将这些相关方法清晰地组合在一起,例如:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
SKPaymentQueue.default().addTransactionObserver(self)
return true
}
func applicationWillTerminate(_ application: UIApplication) {
SKPaymentQueue.default().remove(self)
}
和
extension AppDelegate: SKPaymentTransactionObserver {
// the `SKPaymentTransactionObserver` methods here
}
请参阅previous revision of this answer 了解 Swift 2 版本。