应用内购买-如何仅还原一种产品

时间:2018-09-20 19:52:27

标签: swift in-app-purchase

我的问题是关于StoreKit。如果我在应用内购买了多个商品,是否只能还原一种产品?因为现在,当我单击时,即使我只购买了其中一项,我也获得了所有可能的应用程序内购买。

我正在使用Kilo Loco的代码。 https://www.youtube.com/watch?v=o3hJ0rY1NNw&t=2546s

class IAPService: NSObject {

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

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

func getProducts() {
    let products: Set = [IAPProducts.nonConsumable.rawValue,  IAPProducts.nonConsumable2.rawValue]
    let request = SKProductsRequest(productIdentifiers: products)
    request.delegate = self
    request.start()
    paymentQueue.add(self)
}

func purchase(product: IAPProducts) {
    guard let productToPurchase = products.filter({ $0.productIdentifier == product.rawValue }).first else { return }
    let payment = SKPayment(product: productToPurchase)
    paymentQueue.add(payment)
}

func restorePurchases() {
    print("restore purchases")
    paymentQueue.restoreCompletedTransactions()
}

}

extension IAPService: SKProductsRequestDelegate {
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
    products = response.products
    for product in response.products {
        print(product.localizedTitle)
    }
}

}

extension IAPService: SKPaymentTransactionObserver {
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
    for transaction in transactions {
        print(transaction.transactionState.status(), transaction.payment.productIdentifier)

        if transaction.transactionState.rawValue == 1
        {
            if ViewController.paketas == 1 {
            UserDefaults.standard.set(11, forKey: "pack1")
            }
            if ViewController.paketas == 2 {
                UserDefaults.standard.set(12, forKey: "pack2")
            }
        }

        if transaction.transactionState.rawValue == 3
        {
            if ViewController.paketas == 1 {
                UserDefaults.standard.set(11, forKey: "pack1")
            }
            if ViewController.paketas == 2 {
                UserDefaults.standard.set(12, forKey: "pack2")
            }
        }

        switch transaction.transactionState {
        case .purchasing: break
        default: queue.finishTransaction(transaction)
        }
    }
}

}

extension SKPaymentTransactionState {
func status() -> String {
    switch self {
    case .deferred: return "deferred"
    case .failed: return "failed"
    case .purchased: return "purchased"
    case .purchasing: return "purchasing"
    case .restored: return "restored"
    }
}

}

任何信息或建议都会很有帮助。

0 个答案:

没有答案