如何在iOS中支持IAP订阅免费试用?

时间:2019-07-15 20:05:27

标签: ios swift in-app-purchase

我有自动续订的订阅。我添加了免费的介绍性优惠-1周。

我的代码:

class IAPManager:NSObject {

    static let shared = IAPManager()
    private override init() {    }

    var products: [SKProduct] = []
    let paymentQueue = SKPaymentQueue.default()

    public func setupPurchases(callback: @escaping(Bool) -> ()) {
        if SKPaymentQueue.canMakePayments() {
            paymentQueue.add(self)
            callback(true)
            return
        }
        callback(false)
    }

    public func getProducts() {
        let identifiers: Set = [
            IAPProducts.auto.rawValue
        ]

        let productRequest = SKProductsRequest(productIdentifiers: identifiers)
        productRequest.delegate = self
        productRequest.start()
    }

    public func purchase(productWith identifier: String) {
        guard let product = products.filter({ $0.productIdentifier == identifier }).first else { return }

        let payment = SKPayment(product: product)
        paymentQueue.add(payment)
    }

    public func restoreCompletedTransactions() {
        paymentQueue.restoreCompletedTransactions()
    }
}
extension IAPManager: SKPaymentTransactionObserver {
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {
            switch transaction.transactionState {
            case .deferred: break
            case .purchasing: break
            case .failed: failed(transaction: transaction)
            case .purchased: completed(transaction: transaction)
            case .restored: restored(transaction: transaction)
            }
        }
    }

    private func failed(transaction: SKPaymentTransaction) {
        if let transactionError = transaction.error as NSError? {
            if transactionError.code != SKError.paymentCancelled.rawValue {
                print("Ошибка транзакции: \(transaction.error!.localizedDescription)")
            }
        }
        paymentQueue.finishTransaction(transaction)
    }

    private func completed(transaction: SKPaymentTransaction) {
        print("success")
        NotificationCenter.default.post(name: NSNotification.Name(transaction.payment.productIdentifier), object: nil)
        paymentQueue.finishTransaction(transaction)
    }

    private func restored(transaction: SKPaymentTransaction) {
        paymentQueue.finishTransaction(transaction)
    }
}



extension IAPManager: SKProductsRequestDelegate {
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        self.products = response.products
        print(self.products.count)
        products.forEach { print($0.localizedTitle) }
    }
}

如何将用户选择的免费试用版发送到Apple服务器?对于自动续订,我只需致电:

iapManager.purchase(productWith: identifier)

如何激活免费试用订阅?

1 个答案:

答案 0 :(得分:0)

免费试用版由Apple自动管理-您只需在App Store Connect中的产品上对其进行配置。苹果将​​允许每个订阅组的每个用户免费试用一次。您只需正常购买产品即可。