7

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

1 Answer 1

8

1. Adding observer

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.

2. Removing observer

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)
}

Useful links


¹ : 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

1
  • Can "your_observer" be a UIViewController(in AppDelegate -> didFinishLaunchingWithOptions)? Lets say the view controller is called TheViewWhereTheyBuy. How can one use SKPaymentQueue.default().add(TheViewWhereTheyBuy)?
    – Kristian
    Commented Oct 19, 2018 at 22:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.