如何使用 RevenueCat 购买耗材?

How to purchase consumables with RevenueCat?

我在购买消耗品的逻辑上遇到困难。基本上我不确定如何继续这个功能:

private var item: Purchases.Package? {
    Items.shared.item
}
Purchases.shared.products(["com.item.id"]) { products in
    guard let item = products.first else { return }
    Purchases.shared.purchaseProduct(item) { transaction, purchaserInfo, error, cancelled in
    // enable some stuff in the app
    }
}
public class Items: ObservableObject {
    public static let shared = Items()
    
    @Published public var item: Purchases.Package?
    
    init() {
        Purchases.shared.products(["com.item.id"]) { products in
            self.item = products.first
        }
    }
}

如果我尝试像上面那样初始化,它会抱怨它是 SKProduct?,并且不能分配给 Purchases.Package?

您好像在取苹果 SKProduct and trying to assign it to a RevenueCat Package

您可以直接使用 SKProduct 调用 .purchase() 方法。

// when your paywall is displayed (or earlier to preload)
var consumableProduct : SKProduct?
Purchases.shared.products(["com.item.id"]) { (products) in
    consumableProduct = products.first
}

// when the user taps the 'Buy' button
guard let product = consumableProduct else {
    return print("Error: No product exists")
}
Purchases.shared.purchaseProduct(product) { (transaction, purchaserInfo, error, userCancelled) in
    // handle purchase
}

推荐方法

建议使用 RevenueCat Offerings/Packages,因为您不需要在您的应用中硬编码特定产品 ID(例如“com.item.id”),并且您可以远程更新内容。

// Offerings are automatically pre-loaded by RevenueCat so
// this should read very quickly from cache
var offering : Purchases.Offering?
Purchases.shared.offerings { (offerings, error) in
    // Add any error handling here
    
    offering = offerings?.current
}

// when the user taps the 'Buy' button

// this assumes your paywall only has one item to purchase.
// you may have a dynamic tableview of items and use `indexPath.row` instead of `first`.
guard let package = offering?.availablePackages.first else {
    print("No available package")
    return
}
Purchases.shared.purchasePackage(package) { (trans, info, error, cancelled) in
    // handle purchase
}