Swift—Easily Add a Scenekit Scene to Your App
Imagine you have a good-looking SceneKit scene you want to add as the background of your app. The only problem is that the app you consider is implemented with UIKit whereas the 3D scene is a SceneKit scene.
No worries, I will show you how easy it is to embed a SceneKit scene to a UIKit based app.
The Initial View
Suppose here is the initial view of your storyboard-based app. This view is controlled by
ViewController.swift. In this view, you want to add a nice SceneKit scene as a background.
The simple steps needed
In order to embed a SceneKit scene to the view above, all you need to do is:
- Embed a SceneKit view to this view (below all the UI elements).
- Connect the SceneKit view with the view controller.
- Add a SceneKit scene to your project.
- Find the scene in the view controller and attach it to the SceneKit view which then displays it.
Let’s get right into it.
Embed A SceneKit View to UIView
First, add a SceneKit view to your storyboard and move it in the view hierarchy such that it does not hide other elements as follows:
Now you have a Scenekit view embedded into your view hierarchy. (Feel free to modify the constraints of the view to make it cover the screen the way you however you like.)
Next, connect the SceneKit view with the
ViewController.swift. Remember to name this connection outlet
Good. Now your view controller knows that there is a SceneKit view attached to it.
Add a Scenekit Scene to your Project
Before showing a scene, you need to have an actual scene in your project. Currently, there is none.
If you do not have a scene of your own, feel free to use Apple’s default scene, the Ship Scene. You can find it and the related assets in my repository, in art.scnassets folder.
Assuming you are using the default scene, drag and drop the
art.scnassets folder to the Project navigator. The Project navigator should now look like this:
Find and Connect the Scenekit Scene to the View
ViewController.swift and simply add these two lines inside
let scene = SCNScene(named: "art.scnassets/ship.scn")!
ScenekitView.scene = scene
The first line finds the SceneKit scene and the second line assigns it to the SceneKit view.
Now, by running the app you should see the Ship Scene appear in the background of your view!
Control the Ship
If you want to make the ship rotate, just add these two lines in-between the two lines above.
let ship = scene.rootNode.childNode(withName: "ship", recursively: true)!ship.runAction(SCNAction.repeatForever(SCNAction.rotateBy(x: 0, y: 2, z: 0, duration: 1)))
I hope you enjoyed this simple walkthrough of adding a SceneKit scene to your app!