Archiving World Map Data for Persistence or Sharing

Serialize and deserialize world map objects for file storage or network transmission.


ARWorldMap conforms to the NSSecureCoding protocol, so you can convert a world map to or from a binary data representation using the NSKeyedArchiver and NSKeyedUnarchiver classes.

Listing 1

Saving an ARWorldMap to a file URL

func writeWorldMap(_ worldMap: ARWorldMap, to url: URL) throws {
    let data = try NSKeyedArchiver.archivedData(withRootObject: worldMap, requiringSecureCoding: true)
    try data.write(to: url)
Listing 2

Loading an ARWorldMap from a file URL

func loadWorldMap(from url: URL) throws -> ARWorldMap {
    let mapData = try Data(contentsOf: url)
    guard let worldMap = try NSKeyedUnarchiver.unarchivedObject(ofClass: ARWorldMap.self, from: mapData)
        else { throw ARError(.invalidWorldMap) }
    return worldMap

To send an ARWorldMap to another device, creating a shared frame of reference for multiuser AR experiences:

  1. On one device, use NSKeyedArchiver as in Listing 1 to convert the world map to a data object. (You don't need to write the data to a file to send it over the network.)

  2. Use the networking technology of your choice to send the resulting data to another device. (For example, in a MultipeerConnectivity session, call send(_:toPeers:with:) to send data, and implement MCSessionDelegate methods on the other device to receive data.)

  3. On the receiving device, use NSKeyedUnarchiver as in Listing 2 to instantiate an ARWorldMap from the data.

See Also