ios - Could not open OBJ file when convert MDLAsset to MDLMesh

与世无争的帅哥 提交于 2020-01-05 02:32:48

问题


I'm working with demonstrating loading and texturing a .OBJ file using ModelIO. This code bellow works fine when I use local file.

guard let url = Bundle.main.url(forResource: "myVase", withExtension: "obj") else {
    fatalError("Failed to find model file.")
}

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

But, when I change my code to use file from my Amazon S3 instead of local file. I got errors: "Could not open OBJ file" & "Failed to get mesh from asset." Here is my code:

let url = URL.init(string: "https://s3.amazonaws.com/myObject/.../object.obj")

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

Note: I made the link public and free to download.


回答1:


I fixed my issue. My issue is that I converted the file before the downloading is finished. Therefore, the local path is created but data is empty because download process hasn't finished yet.

To solve it, I use async to finish downloading first then converting it.

let destination: DownloadRequest.DownloadFileDestination = { _, _ in
   let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
   let fileURL = documentsURL.appendingPathComponent("myVase.obj")     
   return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}

Alamofire.download(urlString, to: destination).response { response in
    if response.error == nil, let filePath = response.destinationURL?.path {
       print(imagePath)
       let myUrl = "file://" + filePath

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


来源:https://stackoverflow.com/questions/49266184/ios-could-not-open-obj-file-when-convert-mdlasset-to-mdlmesh

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!