2

我需要从服务器 URL 导入 3D 模型,但它不能正常工作。这是我的代码:

guard let path = modelPath, !path.isEmpty else {
    fatalError("Failed to find model file path.")
}

guard let modelURL = URL(string: path) else {
    fatalError("Failed to find model URL.")
}

let asset = MDLAsset(url:modelURL)
guard let object = asset.object(at: 0) as? MDLMesh else {
    fatalError("Failed to get mesh from asset.")
}

...在此处崩溃object

4

2 回答 2

3

MDLAsset(url:)不处理从服务器下载模型,它仅用于URLs 指向本地存储。

您必须自己下载它(使用URLSession或像 Alamofire 这样的框架)。

使用示例URLSession

下载任务将返回在回调闭包返回后将被删除的文件的临时位置,因此如果您需要重用该文件,则必须将其重新保存在某处。

tempLocation文件的扩展名为.tmpMDLAsset将无法处理。即使您不需要保留文件,我也没有想出比使用所需的扩展名(.obj即)重新保存它更好的方法。

let fileManager = FileManager.default
let localModelName = "model.obj"
let serverModelURL = URL(...)
let localModelURL = fileManager
        .urls(for: .documentDirectory, in: .userDomainMask[0]
        .appendingPathComponent(localModelName)

let session = URLSession(configuration: .default)
let task = session.downloadTask(with: modelURL) { tempLocation, response, error in
    guard let tempLocation = tempLocation else {
        // handle error
        return
    }

    do {
        // FileManager's copyItem throws an error if the file exist
        // so we check and remove previously downloaded file
        // That's just for testing purposes, you probably wouldn't want to download
        // the same model multiple times instead of just persisting it

        if fileManager.fileExists(atPath: localModelURL.path) {
            try fileManager.removeItem(at: localModelURL)
        }

        try fileManager.copyItem(at: tempLocation, to: localModelURL)

    } catch {
        // handle error
    }

    let asset = MDLAsset(url: localURL)
    guard let object = asset.object(at: 0) as? MDLMesh else {
        fatalError("Failed to get mesh from asset.")
    }
}

task.resume() // don't forget to call resume to start downloading
于 2018-02-15T11:13:33.113 回答
0

我认为 .obj 对象还需要至少一个 .mlt 文件,可能还有一个 .jpg 文件用于纹理,检查是否有错误,因为这些文件丢失

于 2018-02-15T10:10:21.127 回答