Swift:促销产品(使用 RevenueCat)- 缓存 defermentBlock

Swift: Promoted products (with RevenueCat) - Caching the defermentBlock

目前,我正尝试在 RevenueCat 的帮助下将促销产品包含在我的应用程序中。不幸的是它不起作用。 (我正在使用 SwiftUI 1.0,所以仍然使用 AppDelegate。)

到目前为止我做了什么:

我已经按照此处所述在 AppDelegate 中实现了以下功能 (https://docs.revenuecat.com/discuss/5cff570754c3420045b379f3):

  func purchases(_ purchases: Purchases, shouldPurchasePromoProduct product: SKProduct, defermentBlock makeDeferredPurchase: @escaping RCDeferredPromotionalPurchaseBlock){
    let defermentBlock = makeDeferredPurchase
    
  }

问题:

我认为问题是我 运行 defermentBlock 放错了地方。正如此处所述 (https://sdk.revenuecat.com/ios/Protocols/RCPurchasesDelegate.html#/c:objc(pl)RCPurchasesDelegate(im)purchases:shouldPurchasePromoProduct:defermentBlock:),应在应用程序处于正确状态时调用它。

目前我直接在函数中调用defermentBlock是这样的:

func purchases(_ purchases: Purchases, shouldPurchasePromoProduct product: SKProduct, defermentBlock makeDeferredPurchase: @escaping RCDeferredPromotionalPurchaseBlock){
    let defermentBlock = makeDeferredPurchase
    
    // Should buy the product 
    defermentBlock { (transaction, info, error, cancelled) in
        if let purchaserInfo = info {
            Purchases.shared.purchaseProduct(product) { (transaction, purchaserInfo, error, userCancelled) in //this function works for products which are directly bought in the app
                if error == nil && !userCancelled{
                    try? CoreDataManagerNew.shared.updateUserInformation()
                }
            }
        }
    }
    
}

现在我有以下问题:

另一个问题是我无法测试功能。 Apple (https://developer.apple.com/documentation/storekit/in-app_purchase/testing_promoted_in-app_purchases) 建议的方法不知何故不起作用。

非常感谢!

确保您在调用配置之后而不是之前设置 Purchases.shared.delegate = self(有人遇到过这个问题 here)。

然后像这样实现委托函数:

    defermentBlock { (transaction, info, error, cancelled) in
        if let purchaserInfo = info {
            if error == nil && !userCancelled{
                try? CoreDataManagerNew.shared.updateUserInformation()
            }
        }
    }   

请注意,您不必在块内调用 purchaseProduct。调用区块等同于调用 purchaseProduct 并且会打开购买对话框。

通过缓存 defermentBlock,我们的意思是您可以将延迟块保存为对象的 属性,然后在您的应用准备好进行购买时调用它。所以你可以这样做:

    var maybeDeferredPurchase: RCDeferredPromotionalPurchaseBlock? = nil
    
    func purchases(_ purchases: Purchases, shouldPurchasePromoProduct product: SKProduct, defermentBlock makeDeferredPurchase: @escaping RCDeferredPromotionalPurchaseBlock) {
        maybeDeferredPurchase = makeDeferredPurchase
    }

然后,每当您想显示购买弹出窗口时(例如,当屏幕已加载时)执行:

if let defermentBlock = self.maybeDeferredPurchase {
    defermentBlock { (transaction, info, error, cancelled) in
        if let purchaserInfo = info {
            handlePurchaserInfo()
        }
    }
}

要测试它是否有效,您可以在您的设备中打开一个 link,例如 itms-services://?action=purchaseIntent&bundleId=<YOUR_BUNDLE_ID>&productIdentifier=<YOUR_SKPRODUCT_ID>。例如,在我的测试应用程序中它是 itms-services://?action=purchaseIntent&bundleId=com.revenuecat.sampleapp&productIdentifier=com.revenuecat.lifetime.199.99.