Adding In-App Purchases to a SwiftUI App

March 22, 2021
|
Kendall Gelner
A programmer doing app developmenta
Photo by
Firos nv

There are lots of articles on adding StoreKit payments to a UIKit based iOS application.  SwiftUI brings a new approach to application structure, and as such deserves a fresh look at approaches to adding in-app purchases (IAPs) to your application.

To start with, you might be wondering - what kinds of payments should I even add?  Single purchases?  Subscriptions?  Something like a tip jar?

Regardless of the approach you eventually choose, we'll look at how to architect a SwiftUI application to add payment options.  We'll explore some good approaches you can take to adding payments to your application and have your SwiftUI application react to purchases from users as they occur.

SwiftUI - Designed for State Changes

SwiftUI works primarily by reacting to application data changing state.  As the state changes, portions of your views are modified, or even hidden/revealed.  Navigation items may react differently depending on the application state.

That works great for user data in your application, but we can make use of that approach for purchases in SwiftUI applications as well!  So to start with, you'll want to define some kind of data source holding a purchase state that your application UI can be built around, to limit access to parts of your application you want paid users to make use of or view.

To keep things simple to start, we'll describe possible kinds of data you can hold purchase activity in, how to write code to handle purchase activity with StoreKit, or use a framework like Nami which manages StoreKit transactions for you and can work with data stores like the ones described below.

What kinds of basic data would you want for different kinds of purchases you might support?

Note:  this article uses embedded gists for code samples that may not display on mobile devices if you are seeing an AMP version of this blog.  If you do not see the code samples below, follow this link.

Subscriptions

As subscriptions are a model where a customer gives you money over time in return for some continuing value of your application, it's a good idea to keep in mind the customer journey with your application - are they brand new?  Might they have been using your app for some time and are about to subscribe?  If they have subscribed, are they going to renew, or have they opted to cancel a current subscription and let it just run out?

Fundamentally, the simplest things you would want to track for a subscription are:

Just from those, you can adjust displays in your application to access content, or to provide some additional messaging as the end of a subscription draws near.

One-Time Purchases

This is what most people think of when they talk about In-App Purchases. In this case, the purchase is made only once and lasts forever.  So it's enough to simply track if something is purchased.

Consumable Purchases

Consumable purchases allow a user to make the same purchase more than once.  Two common use cases are coin packs in games and apps that let you buy and spend credits.  For another uses case of consumable purchases, see our guide on creating a tip jar for your app.

Since users can make a purchase more than once, it's a good idea to keep track of how many times they may have purchased, for either messaging around thanking them for each purchase or adapting the application to reward multiple purchases in some way as well as the user’s credit balance:

You can add more details around any of those items, but those are great starting places.

Where to Put Purchase Data?

When you decide what kind of purchase data you want to preserve and react to, you then need to decide how to store it in a way that a SwiftUI application can react to it.  In order to do that, you can make use of the Combine framework, which allows you to have an object that publishes changes.  For SwiftUI, that means making an ObservableObject, with Published properties that correspond to the kinds of things you'll be looking for.

Creating your ObservableObject

An Observable object is made by declaring one or more Published properties, that when changed will notify any views using the properties.  

For this example, we’ll create an ObservableObject for a subscription.

Then you can either add methods to the ObservableObject to alter the Published properties as needed, or modify them externally via some other code.  An example of setting up a listener for an Observable object to change purchase state for the object above would be to add an init like so:

When you process a purchase with StoreKit, check to see that the purchase has completed, and then send a notification that triggers the ObservableObject to update values:

Note that properly validating a purchase requires looking at the receipt which should be done on a server.  Take a look at this blog post to get started.

Correctly updating subscription state over time also requires a server to process Apple’s Server to Server notifications and correctly update a model of the customer’s subscription lifecycle.  This is beyond the scope of this article.  

If you are using the Nami ML platform, we automatically manage the subscription lifecycle for you.  The code sample below provides an example of fully managing a customer’s access to a subscription in a SwiftUI app.

Creating and Accessing ObservableObject

Once you have an ObservableObject, you'll need to be able to use it for a variety of views across your application.  You also want to create that ObservableObject as early as possible, since purchase messages might be triggered as soon as your application launches.

You could simply create an instance of the object and pass it into every view via an initializer, but chances are you will not need to know about purchase status in every view.  Thus, it's easier to add your ObservableObject into the application environment where any view can access it directly without having to have been passed in the object.

The best place to do setup and add the ObservableObject to the environment is in your App class, where your initial Scene is created.

Now in any class that you want to use your ObservableObject properties, you can just add the object from the environment.

Allowing Access to Paid Content and Features

When your users make a purchase, that purchase unlocks an entitlement that grants them access to the paid features of your app.

Now that we have all the basics in place, let’s look at a few different options of how you can grant access to paid features in your app.

View Visibility

You can optionally display a view, based on the current state of purchases.

You can make an even more complex choice, deciding to display a view based not just on purchase state, but on some other variable like subscription expiration.

In this example, there may be a completely different view for a paid subscriber than there is for a free user.

Conditional View Content

In the same way, you can conditionally add whole views, you can also opt to change content based on the purchase state.

This can be a good way to show paid features that exist on a view or enable a disabled button that does not work for a free customer.

Navigation

When you have a button that accesses paid content in your application, you can check if the user has the correct access for that content.

If they do, allow them to see the content, otherwise you can present your paywall with your purchase options.

This is a general pattern you may use to protect paid content in your app.

Integrating Full Purchase Support

A full StoreKit implementation is beyond the scope of this article and requires some updates to your app code as well as some server-side components as well.  This talk has a good overview of the basics.

The Nami platform also takes care of the complexity of StoreKit integration so you can focus on other aspects of your app.  Check out our SwiftUI page or Quickstart Guide for an overview.

SwiftUI makes it very easy to modify UI in reaction to purchases via waiting for state changes.  You should think about adding support for purchases as early as possible during the design of your application, so the integration of purchase boundaries feels as natural as possible and doesn't cause you extra work rearranging UI to support purchases later.

Sign up to our newsletter

Get the latest articles delivered straight to your inbox.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Nami logo white

Focus on your app experience

We'll handle the subscriptions.

Portrait photo of blog author
Kendall Gelner

Kendall Gelner is an iOS Architect at Nami ML. He is well regarded in the iOS development community for his technical knowledge and platform experience going back to the App Store launch. The last SDK Kendall was responsible for shipped inside of some of the most widely installed apps, reaching more than 200 million devices.

Similar articles

Read similar articles to this one

Quotes mark

Testimonials

Some client stories

"We spent hours researching the best ways to implement subscriptions and after many failed attempts we found Nami. We were able to go live with subscriptions in our Apple and Android apps in a matter of days."
Client portrait
Brian Pedone
Founder
Quiet Punch
Quiet Punch
"Nami helped us achieve a cross-platform solution for managing and sellingsubscriptions on Apple and Google. The Nami platform was flexible enough to handleour business requirements for in-app purchasing, allowing us to focus on our client'score domain and domain logic.”
Client Name
Client role
Company name
"Nami helped us achieve a cross-platform solution for managing and selling subscriptions on Apple and Google. The Nami platform was flexible enough to handle our business requirements for in-app purchasing, allowing us to focus on our client's core domain and domain logic."
Melody Morgan
Director, Engineering
Diamond
Diamond
"We spent hours researching the best ways to implement subscriptions and after many failed attempts we found Nami. We were able to go live with subscriptions in our Apple and Android apps in a matter of days."
Brian Pedone
Founder
Quiet Punch
Quiet Punch
"It took a couple of hours to incorporate their easy to use SDK. Nami provides a monetization machine learning solution, a paywall displaying what a user can purchase, and a whole suite of other useful features. As a result, it saved me development cycles so I could focus on other important things."
Mark Lapasa
Android Developer
Toronto App Factory
Toronto App Factory
"After spending a few days trying to implement subscriptions, I found Nami ML. I was able to complete in-app subscriptions within less than 3 hours."
Tanin Rojanapiansatith
iOS Developer
Transcrybr
Transcrybr

The best subscription experience starts with Nami

Get connected with one of our product experts to get started with your journey with Nami today.