Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get call back of a delegate method inside of a manager class swift

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading