我在Sprite Kit中制作游戏。
我有IAPProducts Swift File代码:
import Foundation
enum IAPProducts: String {
case nonConsumable1 = "Kingdom.Lion"
case nonConsumable2 = "Kingdom.Sheep"
}
和IAPService.Swift文件,代码为:
import Foundation
import StoreKit
var lionpurchased = false
var sheeppurchased = false
class IAPService: NSObject {
private override init() {}
static let shared = IAPService()
var products = [SKProduct]()
let paymentQueue = SKPaymentQueue.default()
func getProducts() {
let products: Set = [
IAPProducts.nonConsumable1.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)
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"
}
}
}
问题是我需要知道购买了哪些NonConsumable产品?我需要知道我应该检查什么等于IAPProducts.nonConsumable1.rawValue和IAPProducts.nonConsumable2.rawValue
答案 0 :(得分:0)
在paymentQueue(_:updatedTransactions:)
方法中,您需要检查每笔交易的状态。如果状态为.purchased
,请查看交易的付款。付款productIdentifier
会告诉您购买了哪些应用内购买。
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
if transaction.state == .purchased {
let productId = transaction.payment.productIdentifier
// Your code to handle the completed purchase of this IAP
}
queue.finishTransaction(transaction)
}
}