Swift iOS ARKit从文件NSKeyedUnarchiver NSKeyedArchiver加载ARWorldMap数据

时间:2018-07-28 13:58:40

标签: ios swift arkit nskeyedarchiver nskeyedunarchiver

我正在尝试保存,然后将ARKit ARWorldMap加载到本地文件。我似乎可以节省开支了:

func saveWorldMap() {

    ARView?.session.getCurrentWorldMap { [unowned self] worldMap, error in

        guard let map = worldMap else { return }

        do {
            let data = try NSKeyedArchiver.archivedData(withRootObject: map, requiringSecureCoding: true)
            do {
                let url: URL = URL(fileURLWithPath: self.worldMapFilePath("test"))
                try data.write(to: url)
            } catch {
                fatalError("Can't write to url")
            }
        } catch {
            fatalError("Can't encode map")
        }
    }

}


func worldMapFilePath(_ fileName: String) -> String {

    createWorldMapsFolder()
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0] as String
    let filePath: String = "\(documentsDirectory)/WorldMaps/WorldMap_\(fileName)"
    if FileManager().fileExists(atPath: filePath) { try! FileManager().removeItem(atPath: filePath) }
    return filePath

}

func createWorldMapsFolder() {

    let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
    if let documentDirectoryPath = documentDirectoryPath {

        let replayDirectoryPath = documentDirectoryPath.appending("/WorldMaps")
        let fileManager = FileManager.default

        if !fileManager.fileExists(atPath: replayDirectoryPath) {

            do {
                try fileManager.createDirectory(atPath: replayDirectoryPath, withIntermediateDirectories: false, attributes: nil)
            } catch {
                print("Error creating Captures folder in documents dir: \(error)")
            }
        } else {
            print("WorldMaps folder already created. No need to create.")
        }
    }

}

当我尝试然后加载保存的ARWorldMap时出现问题:

func loadWorldMap() {

    guard let data = retrieveWorldMapDataForFilename("test") else { fatalError("Can't get data") }

    do {
        let worldMap = try NSKeyedUnarchiver.unarchivedObject(ofClass: ARWorldMap.self, from: data)
        startSession(options: [.resetTracking, .removeExistingAnchors], initialWorldMap: worldMap)

    } catch {
        fatalError("Can't get worldMap")
    }        

}

func retrieveWorldMapDataForFilename(_ filename: String) -> Data? {

    let url: URL = URL(fileURLWithPath: self.worldMapFilePath(filename))
    do {
        let data = try Data(contentsOf: url)
        return data
    } catch {
        fatalError("Can't get data at url:\(url)")
    }

}

当我尝试用ARWorldMaploadWorldMap()加载保存的retrieveWorldMapDataForFilename(_ filename: String)时,在this text (an another text) "and a text" and again a text 的底部fatalError被捕获,并显示以下错误

  

线程1:致命错误:无法在以下位置获取数据   网址:file:/// var / mobile / Containers / Data / Application / 924B012B-B149-4BA7-BFC2-BB79849D866F / Documents / WorldMaps / WorldMap_test

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

看看您的代码,问题出在以下功能之内:

func worldMapFilePath(_ fileName: String) -> String {}

当您保存世界地图时,此功能可以正常工作,但是当您尝试检索它时,文件将被删除。

如果您记录实际错误:

fatalError("Error = \(error)")

而不是使用它:

fatalError("Can't get data at url:\(url)")

您将收到以下错误消息:

  

“无法打开文件“ WorldMap_test”,因为没有这样的文件   文件。

比您的问题中提供的信息更丰富的信息,例如:

  

无法获取数据   网址:file:/// var / mobile / Containers / Data / Application / 924B012B-B149-4BA7-BFC2-BB79849D866F / Documents / WorldMaps / WorldMap_test

这样一些简单的更改就可以解决您的问题。

首先,我建议将呼叫移至createWorldMapsFolder()viewDidLoad

第二次更改您的func worldMapFilePath(_ fileName: String) -> String {},如下所示:

  func worldMapFilePath(_ fileName: String) -> String {

        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let documentsDirectory = paths[0] as String
        let filePath: String = "\(documentsDirectory)/WorldMaps/WorldMap_\(fileName)"
        return filePath

    }

然后将您的fileExists调用移至saveWorldMap函数,例如:

func saveWorldMap() {

        sceneView.session.getCurrentWorldMap { [unowned self] worldMap, error in

            guard let map = worldMap else { return }

            do {
                let data = try NSKeyedArchiver.archivedData(withRootObject: map, requiringSecureCoding: true)

                do {
                    let worldMapPath = self.worldMapFilePath("test")

                    if FileManager().fileExists(atPath: worldMapPath) { try! FileManager().removeItem(atPath: worldMapPath) }

                    let url: URL = URL(fileURLWithPath: worldMapPath)
                    try data.write(to: url)

                } catch {
                    fatalError("Can't write to url")
                }
            } catch {
                fatalError("Can't encode map")
            }
        }

    }

希望有帮助...