I have IAP working inside my app but can't help but to feel I'm doing something wrong with when to call. When should I be calling these methods?
SKPaymentQueue.default().add(self)
and when to call
SKPaymentQueue.default().remove(self)
Thanks guys
You should add an observer to the queue as soon as possible. Somewhere in your application(_:didFinishLaunchingWithOptions:)
function in your app delegate.
Mentioned in the add(_:)
documentation:
Your application should add an observer to the payment queue during application initialization.
Your app should basically always be ready to process a transaction and mark it as finished¹. Because any unhandled transactions are added back to the queue until you have handled them:
Make sure that the observer is ready to handle a transaction at any time, not just after you add a transaction to the queue. [...] if your app fails to mark a transaction as finished, StoreKit calls the observer every time your app is launched until the transaction is properly finished.
There is no reason to remove yourself as observer during normal app use. As you should always be able to process any incoming transactions.
That means you should remove yourself as late as possible. The best place for that is in the applicationWillTerminate(_:)
function in the app delegate:
This method lets your app know that it is about to be terminated and purged from memory entirely. You should use this method to perform any final clean-up tasks for your app [...]
Removing as observer is not as explicitly talked about in Apple's documentation, but you can see it in a code snippet under listing 2 in their In-App Purchase Best Practices tech note:
// Called when the application is about to terminate.
func applicationWillTerminate(_ application: UIApplication) {
// Remove the observer.
SKPaymentQueue.default().remove(your_observer)
}
¹ : only mark a transaction finished when it makes sense, whatever that means for your app:
Your application should call
finishTransaction:
only after it has successfully processed the transaction and unlocked the functionality purchased by the user
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With