如何在管理器中回调委托方法 class swift

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

这是我的应用内购买 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)")
        }
    }
    
}

在我的视图控制器中,我这样调用:

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

当它调用函数名称“checkPaymentEnabled”并检查if(SKPaymentQueue.canMakePayments())是否启用时它会自动触发以下委托方法:

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
    }

我想从我的视图控制器中的委托响应中获取产品列表。我该怎么做?

您可以使用回调,因此将其添加到您的 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
}

在函数内部 ViewController

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