IAP自动续订,SKPaymentQueue更新交易功能未响应

时间:2019-06-14 17:22:52

标签: ios swift in-app-purchase

我已经在应用程序购买中实现了针对应用程序中自动更新订阅的功能,但是我尝试在购买完成后实施一些功能。

以下是我的IAP订阅服务

class SubscriptionService: NSObject {


static let sessionIdSetNotification = Notification.Name("SubscriptionServiceSessionIdSetNotification")
static let optionsLoadedNotification = Notification.Name("SubscriptionServiceOptionsLoadedNotification")
static let restoreSuccessfulNotification = Notification.Name("SubscriptionServiceRestoreSuccessfulNotification")
static let purchaseSuccessfulNotification = Notification.Name("SubscriptionServiceRestoreSuccessfulNotification")

static let shared = SubscriptionService()

private var purchasedProductIdentifiers: Set<ProductIdentifier> = []

var productDidPurchased: (() -> Void)?

var hasReceiptData: Bool {
    return loadReceipt() != nil
}

var options: [Subscription]? {
    didSet {
        NotificationCenter.default.post(name: SubscriptionService.optionsLoadedNotification, object: options)
    }
}

func loadSubscriptionOptions() {

    let products: Set = ["productIDS"]

    let request = SKProductsRequest(productIdentifiers: products)
    request.delegate = self
    request.start()
}

func uploadReceipt(completion: ((_ success: Bool) -> Void)? = nil) {
    if let receiptData = loadReceipt() {

    }
}

private func loadReceipt() -> Data? {
    guard let url = Bundle.main.appStoreReceiptURL else {
        return nil
    }

    do {
        let data = try Data(contentsOf: url)
        return data
    } catch {
        print("Error loading receipt data: \(error.localizedDescription)")
        return nil
    }
}

func purchase(subscription: Subscription) {
    let payment = SKPayment(product: subscription.product)
    print("Product being bought: \(payment)")
    SKPaymentQueue.default().add(payment)
}

func restorePurchases() {
    SKPaymentQueue.default().restoreCompletedTransactions()
}
 }

 extension SubscriptionService: SKProductsRequestDelegate {
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
    options = response.products.map { Subscription(product: $0) }
    print("in here 1")
    print(options!)
   // let purchased = UserDefaults.standard.bool(forKey: "com.mylawnow.sub.allaccess")
    //print("Purchased\(purchased)")
    print("in here 2")
}

func request(_ request: SKRequest, didFailWithError error: Error) {
    if request is SKProductsRequest {
        print("Subscription Options Failed Loading: \(error.localizedDescription)")
    }
}
}

// --------------------------------------------- ----------------

这部分似乎不起作用。这些功能似乎都没有触发(我已经实现了打印语句,以查看它们是否曾经被击中,但似乎没有。)

extension SubscriptionService: SKPaymentTransactionObserver{

public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
    print("updating")
    for transaction in transactions {
        switch (transaction.transactionState) {
        case .purchased:
            print("purchased made")
            complete(transaction: transaction)
            break
        case .failed:
            print("purchased failed")
            fail(transaction: transaction)
            break
        case .restored:
            print("restored")
            restore(transaction: transaction)
            break
        case .deferred:
            print("purchase deferred")
            break
        case .purchasing:
            print("purchase being made")
            break
        }
    }
}

我假设完成购买后,应使用完整功能执行某些功能。

private func complete(transaction: SKPaymentTransaction) {
    print("completed...")
    deliverPurchaseNotificationFor(identifier: transaction.payment.productIdentifier)
    SKPaymentQueue.default().finishTransaction(transaction)
}

private func restore(transaction: SKPaymentTransaction) {
    guard let productIdentifier = transaction.original?.payment.productIdentifier else { return }

    deliverPurchaseNotificationFor(identifier: productIdentifier)
    print("identifier: \(productIdentifier)")
    SKPaymentQueue.default().finishTransaction(transaction)
}

private func fail(transaction: SKPaymentTransaction) {
    print("failed...")
    if let transactionError = transaction.error as NSError?,
        let localizedDescription = transaction.error?.localizedDescription,
        transactionError.code != SKError.paymentCancelled.rawValue {
        print("Transaction Error: \(localizedDescription)")
    }

    SKPaymentQueue.default().finishTransaction(transaction)
}

private func deliverPurchaseNotificationFor(identifier: String?) {
    guard let identifier = identifier else { return }

   purchasedProductIdentifiers.insert(identifier)
   UserDefaults.standard.set(true, forKey: identifier)
   NotificationCenter.default.post(name: .IAPHelperPurchaseNotification, object: identifier)
}

}

1 个答案:

答案 0 :(得分:0)

所以我发现了错误。在我的loadSubscriptions函数中,我需要向SKPaymentQueue应用观察者。因此应如下所示:

func loadSubscriptionOptions() {
    let products: Set = ["productIDS"]

    let request = SKProductsRequest(productIdentifiers: products)
    request.delegate = self
    request.start()
     SKPaymentQueue.default().add(self) //--> this line is needed
}