MDLAsset(url:)
不处理从服务器下载模型,它仅用于URL
s 指向本地存储。
您必须自己下载它(使用URLSession
或像 Alamofire 这样的框架)。
使用示例URLSession
:
下载任务将返回在回调闭包返回后将被删除的文件的临时位置,因此如果您需要重用该文件,则必须将其重新保存在某处。
该tempLocation
文件的扩展名为.tmp
,MDLAsset
将无法处理。即使您不需要保留文件,我也没有想出比使用所需的扩展名(.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