Last active
February 26, 2020 22:38
-
-
Save HassanElDesouky/14c442a2714d1676f6700312c383fa48 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// IAPService.swift | |
// Remelo | |
// | |
// Created by Hassan El Desouky on 2/23/20. | |
// Copyright © 2020 Hassan El Desouky. All rights reserved. | |
// | |
import Foundation | |
import StoreKit | |
enum IAPProduct: String { | |
case monthlyAutoRenewableSubscription = "" | |
case yearlyAutoRenewwableSubscription = "" | |
} | |
class IAPService: NSObject { | |
private override init() { } | |
static let shared = IAPService() | |
var products = [SKProduct]() | |
let paymentQueue = SKPaymentQueue.default() | |
func getProducts() { | |
let products: Set = [IAPProduct.monthlyAutoRenewableSubscription.rawValue, | |
IAPProduct.yearlyAutoRenewwableSubscription.rawValue] | |
let request = SKProductsRequest(productIdentifiers: products) | |
request.delegate = self | |
request.start() | |
paymentQueue.add(self) | |
} | |
func purchase(product: IAPProduct) { | |
guard let productToPurchace = products.filter({ $0.productIdentifier == product.rawValue }).first else { return } | |
let payment = SKPayment(product: productToPurchace) | |
paymentQueue.add(payment) | |
} | |
func restorePurchases() { | |
print("Restored") | |
paymentQueue.restoreCompletedTransactions() | |
} | |
} | |
extension IAPService: SKProductsRequestDelegate { | |
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { | |
self.products = response.products | |
for product in 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 == .purchasing { | |
break | |
} else { | |
queue.finishTransaction(transaction) | |
} | |
} | |
} | |
} | |
extension SKPaymentTransactionState { | |
func status() -> String { | |
switch self { | |
case .deferred: | |
return "deferred" | |
case .purchased: | |
return "purchased" | |
case .failed: | |
return "failed" | |
case .purchasing: | |
return "purchasing" | |
case .restored: | |
return "restored" | |
@unknown default: | |
return "" | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment