SHARE
TWEET

Untitled

a guest Nov 19th, 2019 80 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //
  2. //  IAPHandler.swift
  3. //  
  4. //
  5. //  Created by Jonathan Wukitsch on 9/17/19.
  6. //  Copyright © 2016-2019 Jonathan Wukitsch. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10. import StoreKit
  11.  
  12. enum IAPHandlerAlertType {
  13.     case setProductIds
  14.     case disabled
  15.     case restored
  16.     case purchased
  17.    
  18.     var message: String {
  19.         switch self {
  20.         case .setProductIds: return "Product IDs not set. Call setProductIDs method."
  21.         case .disabled: return "Purchases are disabled on this device."
  22.         case .restored: return "Your purchases have successfully been restored."
  23.         case .purchased: return "Your purchase was successful."
  24.         }
  25.     }
  26. }
  27.  
  28. class IAPHandler: NSObject {
  29.    
  30.     // MARK: - Shared Object
  31.     // MARK: -
  32.     static let shared = IAPHandler()
  33.     private override init() {}
  34.    
  35.     // MARK: - Properties
  36.     // MARK: - Private
  37.     fileprivate var productIds = [String]()
  38.     fileprivate var productID = ""
  39.     fileprivate var productsRequest = SKProductsRequest()
  40.     fileprivate var fetchProductCompletion: (([SKProduct]) -> Void)?
  41.    
  42.     fileprivate var productToPurchase: SKProduct?
  43.     fileprivate var purchaseProductCompletion: ((IAPHandlerAlertType, SKProduct?, SKPaymentTransaction?) -> Void)?
  44.    
  45.     // MARK: - Public
  46.     var isLogEnabled: Bool = true
  47.    
  48.     // MARK: - Methods
  49.     // MARK: - Public
  50.    
  51.     // Set product IDs
  52.     func setProductIds(ids: [String]) {
  53.         self.productIds = ids
  54.     }
  55.    
  56.     // Make a purchase
  57.     func canMakePurchases() -> Bool { return SKPaymentQueue.canMakePayments() }
  58.    
  59.     func purchase(product: SKProduct, completion: @escaping ((IAPHandlerAlertType, SKProduct?, SKPaymentTransaction?) -> Void)) {
  60.        
  61.         self.purchaseProductCompletion = completion
  62.         self.productToPurchase = product
  63.        
  64.         if self.canMakePurchases() {
  65.             let payment = SKPayment(product: product)
  66.             SKPaymentQueue.default().add(self)
  67.             SKPaymentQueue.default().add(payment)
  68.            
  69.             log("Product to purchase: \(product.productIdentifier)")
  70.             productID = product.productIdentifier
  71.         } else {
  72.             completion(IAPHandlerAlertType.disabled, nil, nil)
  73.         }
  74.     }
  75.    
  76.     // Restore purchases
  77.     func restorePurchase() {
  78.         SKPaymentQueue.default().add(self)
  79.         SKPaymentQueue.default().restoreCompletedTransactions()
  80.     }
  81.    
  82.     // Fetch available IAP products
  83.     func fetchAvailableProducts(completion: @escaping (([SKProduct]) -> Void)) {
  84.        
  85.         self.fetchProductCompletion = completion
  86.  
  87.         if self.productIds.isEmpty {
  88.             log(IAPHandlerAlertType.setProductIds.message)
  89.             fatalError(IAPHandlerAlertType.setProductIds.message)
  90.         } else {
  91.             productsRequest = SKProductsRequest(productIdentifiers: Set(self.productIds))
  92.             productsRequest.delegate = self
  93.             productsRequest.start()
  94.         }
  95.     }
  96.    
  97.     // MARK: - Private
  98.     fileprivate func log <T> (_ object: T) {
  99.         if isLogEnabled {
  100.             NSLog("\(object)")
  101.         }
  102.     }
  103. }
  104.  
  105. // MARK: - Product Request Delegate and Payment Transaction Methods
  106. // MARK: -
  107. extension IAPHandler: SKProductsRequestDelegate, SKPaymentTransactionObserver {
  108.    
  109.     // Request IAP products
  110.     func productsRequest(_ request:SKProductsRequest, didReceive response: SKProductsResponse) {
  111.        
  112.         if (response.products.count > 0) {
  113.             if let completion = self.fetchProductCompletion {
  114.                 completion(response.products)
  115.             }
  116.         }
  117.     }
  118.    
  119.     func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
  120.         if let completion = self.purchaseProductCompletion {
  121.             completion(IAPHandlerAlertType.restored, nil, nil)
  122.         }
  123.     }
  124.    
  125.     // IAP payment queue
  126.     func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
  127.         for transaction:AnyObject in transactions {
  128.             if let trans = transaction as? SKPaymentTransaction {
  129.                 switch trans.transactionState {
  130.                 case .purchased:
  131.                     log("Product purchase completed")
  132.                     SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
  133.                     if let completion = self.purchaseProductCompletion {
  134.                         completion(IAPHandlerAlertType.purchased, self.productToPurchase, trans)
  135.                     }
  136.                     break
  137.                 case .failed:
  138.                     log("Product purchase failed")
  139.                     SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
  140.                     break
  141.                 case .restored:
  142.                     log("Product restored")
  143.                     SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
  144.                     break
  145.                 default:
  146.                     break
  147.                 }
  148.             }
  149.         }
  150.     }
  151. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top