Home > front end >  How to get call back of a delegate method inside of a manager class swift
How to get call back of a delegate method inside of a manager class swift

Time:01-25

This is my In-App purchase class:

import Foundation
import StoreKit

class InAppPurchaseManager: NSObject {
    static let shared = InAppPurchaseManager()
    private override init() { }
    
    // First
    // We need to check if user canMakePayments
    func checkPaymentEnabled(for productID: [String]) {
        if(SKPaymentQueue.canMakePayments()) {
            print("User can make payment is enabled")
            let request = SKProductsRequest(productIdentifiers: Set(productID))
            request.delegate = self
            request.start()
        } else {
            print("Please enable make payment.")
        }
    }
    
    // Third
    // Declare the buy product func
    func buyProduct(product: SKProduct) {
        let pay = SKPayment(product: product)
        SKPaymentQueue.default().add(self)
        SKPaymentQueue.default().add(pay as SKPayment)
    }
}

extension InAppPurchaseManager: SKProductsRequestDelegate, SKPaymentTransactionObserver {
    // Second
    // checkPaymentEnabled function will trigger this method and we will add products in our productsList
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        var productList = [SKProduct]()
        let myProduct = response.products
        for product in myProduct {
            print("product added")
            print(product.productIdentifier)
            print(product.localizedTitle)
            print(product.localizedDescription)
            print(product.price)
            productList.append(product)
        }
        //Send back the product list
    }
    
    // Fourth
    // We will get the purchase confirmation here after tapping on purchase
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction: AnyObject in transactions {
            if let trans = transaction as? SKPaymentTransaction {
                //print(trans.error)
                switch trans.transactionState {
                case .purchased:
                    let prodID = trans.payment.productIdentifier
                    print("purchased \(prodID)")
                    queue.finishTransaction(trans)
                case .failed:
                    print("buy failed")

                    queue.finishTransaction(trans)
                    break
                case .purchasing:
                    print("Customer is in the processing of purchase")
                    break
                case .restored:
                    print("Restored")
                    queue.finishTransaction(trans)
                    break
                case .deferred:
                    print("deferred")
                    break
                default:
                    print("Default")
                    break
                }
            } else {
                print("Unknown error!")

            }
        }
    }
    
    // Fifth
    // This will be triggered when user restore a purchase
    func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
        print("transactions restored")
        for transaction in queue.transactions {
            let t: SKPaymentTransaction = transaction
            let prodID = t.payment.productIdentifier as String
            print("restored \(prodID)")
        }
    }
    
}

In my view controller I am calling this:

override func viewDidLoad() {
        super.viewDidLoad()
//        checkPaymentEnabled()
        InAppPurchaseManager.shared.checkPaymentEnabled(for: productIDs)
    }

When It calls the function name "checkPaymentEnabled" and check if(SKPaymentQueue.canMakePayments()) is enabled It automatically triggers the below delegate method:

func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        var productList = [SKProduct]()
        let myProduct = response.products
        for product in myProduct {
            print("product added")
            print(product.productIdentifier)
            print(product.localizedTitle)
            print(product.localizedDescription)
            print(product.price)
            productList.append(product)
        }
        //Send back the product list
    }

I want to get the product list from this delegate response in my view controller. How can I do it?

CodePudding user response:

You can use a callback , so add this to your InAppPurchaseManager class

var getValues:([SKProduct] -> ())? // Step 1  

func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
    var productList = [SKProduct]()
    let myProduct = response.products
    for product in myProduct {
        print("product added")
        print(product.productIdentifier)
        print(product.localizedTitle)
        print(product.localizedDescription)
        print(product.price)
        productList.append(product)
    }
    //Send back the product list
    getValues?(productList)    // Step 2
}

And inside the function the ViewController

InAppPurchaseManager.shared.getValues = { [weak self] products in  // Step 3 
  print(products) 
} 
InAppPurchaseManager.shared.checkPaymentEnabled(for: productIDs)
  •  Tags:  
  • Related