Restoring the World Map

The last thing we need to do to make the first version of our little app work is to load the world map. We already added a property to ARViewController to control when the world map should be loaded. Add the highlighted code to viewWillAppear(_:) right above the line where we set the session delegate:

 override​ ​func​ ​viewWillAppear​(_ animated: ​Bool​) {
 super​.​viewWillAppear​(animated)
 
 // Create a session configuration
 let​ configuration = ​ARWorldTrackingConfiguration​()
  configuration.planeDetection = .horizontal
 
»if​ shouldRestore {
»do​ {
»let​ data = ​try​ ​Data​(contentsOf: ​FileManager​.​mapDataURL​())
»let​ worldMap = ​try​ ​NSKeyedUnarchiver​.​unarchivedObject​(
» ofClass: ​ARWorldMap​.​self​, from: data)
» configuration.initialWorldMap = worldMap
» } ​catch​ {
»printLog​(​"error: ​​(​error​)​​"​)
» }
» }
 
 
 // Run the view's session
  sceneView.session.​run​(configuration)
 }

When shouldRestore is set to true, we load the world map data from the documents directory and try to unpack it from the archive. If this is successful, we set the loaded world map to the initialWorldMap property of the world tracking configuration. This is all we have to do to reload a stored world map—it could hardly be simpler.

Build and run the app on your iPhone and try it out. Add an anchor, add some text, and verify that the world map with the text is loaded when you leave and reenter the 10-meter radius around the stored location.

You might have noticed that the accuracy of the stored location is sometimes not that good. You’ll improve that in the exercises.

That’s it! The first version of our Scavenger Hunt app is finished. Don’t forget to work through the exercises to improve on this initial version.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.137.64