Skip to content

Instantly share code, notes, and snippets.

@eunjiChung
Last active March 11, 2021 09:46
Show Gist options
  • Save eunjiChung/6d8dec748248083952ba8ca4f4377382 to your computer and use it in GitHub Desktop.
Save eunjiChung/6d8dec748248083952ba8ca4f4377382 to your computer and use it in GitHub Desktop.
extension IAPHelper: SKPaymentTransactionObserver {
public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
switch (transaction.transactionState) {
case .purchased:
complete(transaction: transaction)
break
case .failed:
fail(transaction: transaction)
break
case .restored:
restore(transaction: transaction)
break
case .deferred, .purchasing:
break
@unknown default:
fatalError()
}
}
}
// 구입 성공
private func complete(transaction: SKPaymentTransaction) {
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)
SKPaymentQueue.default().finishTransaction(transaction)
}
// 구매 실패
private func fail(transaction: SKPaymentTransaction) {
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)
}
// 구매한 인앱 상품 키를 UserDefaults로 로컬에 저장
private func deliverPurchaseNotificationFor(identifier: String?) {
guard let identifier = identifier else { return }
let dict: ProductInfo = [IAPProductKey.purchased: true,
IAPProductKey.validated: false]
UserDefaults.standard.setValue(dict, forKey: identifier)
requestValidation(productId: identifier)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment