How to save function reference in Swift 2?

The root problem is that it SkPaymentQueue.defaultQueue().addPayment()doesn't allow you to pass a callback function, and there is no way to pass a function at runtime (which I know) to SKPaymentTransactionObserver. I use the React-native version 0.28to create a module that allows me to make purchases in the application, however I would like to call the Javascript function after completing the purchase in the application.

So I was going to keep the callback link RCTResponseSenderBlockin the class and reference it in SKPaymentTransactionObserver. However, I do not know how to access a function in Swift.

I tried to make the following variable

weak var purchaseCallback: RCTResponseSenderBlock = nil

at the top of the class so that I can install it and refer to it later; however, Swift complains about the following:

Nil cannot initialize specified type 'RCTResponseSenderBlock'

If there is a way to handle function references and / or a better way to make a callback, I would appreciate help!

+4
source share
1 answer

As Brian Chen noted in his comment above, making the variable an option, he did the trick.

Here, how I define a variable that contains a callback:

var purchaseCallback: RCTResponseSenderBlock? = nil

And this is how I save the link to the function from a function called React-native in Swift:

@objc func purchaseProduct(identifier: String, callback successCallback: RCTResponseSenderBlock) {
  purchaseCallback = successCallback
}
+2
source

All Articles