Adding In-App Purchases & GameCenter to My SpriteKit Game

Adding In-App Purchases & GameCenter to My SpriteKit Game
Photo by Arnold Francisca / Unsplash

The Problem With Swift Playgrounds

Listen, I love Swift Playgrounds, it's a great app for learning how to write in SwiftUI. It lowers the bar to entry for many people who are looking to learn to code.

There is a problem though. It's missing core functionality.

With Swift Playgrounds you can not add capabilities to your app that will grant you access to things like GameCenter or In-App Purchases. These are two core features that I believe should be included in Swift Playgrounds. At least if we're to believe that this app is truly designed to create apps for the AppStore.

Converting Swift Playgrounds Project to Xcode

To add this type of functionality to an app created in Swift Playgrounds you will need to convert your playgrounds project to an Xcode project. This is not straightforward (it should be Apple).

The process involves copying/pasting the code from your Swift Playgrounds files into a NEW Xcode project. You have to make sure that your bundle ID is the same if you've already published the app to the AppStore. There are a lot of little details involved when moving from Swift Playgrounds to Xcode. Apple really should create a tool for this.

Adding GameCenter and In-App Purchases

When it comes to adding these two capabilities it's not too difficult or time-consuming. The video above goes over the concepts on a high level, but if you don't wish to watch a video, the basics of it are as follows.

You first need to set up your Leaderboard / Achievement IDs / In-App Purchases within  Apple's developer portal - AppStoreConnect.

Once you've set up the various items that you wish to connect you will need to hook them up using code within Xcode. This is how you can tell your app when and where to execute the required activities for your various items.

My approach, in the video above, is very basic. For GameCenter, I created a class GameKitHelper which handles the bulk of the work. This then gets initiated as a singleton so that I can have access to it globally. From there it's as simple as reporting high scores or unlocking achievements within the code when a player meets specific criteria.

For in-app purchases, the process is very similar. You first need to set up the items you wish to sell within AppStoreConnect and once you've done that you then can pull them into Xcode using a StoreKit configuration file.

From here you'll need to conform to a few different delegates and observers to be able to handle the process of pulling store items from Apple's servers and listening to the transaction as it happens.

The code is fairly simple though and once you've done it once it's easy to replicate for future apps that you might create.

I hope you enjoyed this article and thanks so much for reading it. Please consider subscribing to the newsletter to get notified when I publish again.