Tutorial: MVVM Set Up for a RealityKit SwiftUI Project in Xcode

Quick MVVM Setup For RealityKit SwiftUI Projects

In this tutorial, we will be going over how to set up your SwiftUI-based RealityKit projects in the Model View ViewModel system.

We will start with the Augmented Reality App template in Xcode:

We will be using SwiftUI for the Interface, Swift as the Language, and RealityKit as the Content Technology:

Your project should now look like this:

We will be added in an “ARModel” file, which will contain our actual ARKit and RealityKit code, and an “ARViewModel” file, which will allow us to connect our “ARModel” to our SwiftUI view, and allow our SwiftUI view to interact easily with our “ARModel”.

Add a new Swift struct titled “ARModel” and add the below code required for a basic ARView setup:

Next, add a new Swift class titled “ARViewModel”, which will have a @Published var for our “ARModel”:

Now we need to update the “ARViewContainer” struct to integrate with our new “ARViewModel” class to return the ARView being created in the “ARModel”:

And finally, we need to update the “ContentView” with an @ObservedObject of the “ARViewModel” class, which will allow changes in the ARModel to update our SwiftUI ContentView, and will allow our SwiftUI view to connect to our “ARModel” through the “ARViewModel” class:

And there you have it! This is a setup that I use when setting up RealityKit and ARKit based AR projects. You can see this in use in my tutorial on adding a SwiftUI button to switch between ARKit cameras:

You can access the full GitHub repository for this tutorial setup here:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store