如何通过URLSession下载USDZ?

时间:2019-12-06 08:07:21

标签: swift arkit realitykit

我通过 urlsession 在我的代码中下载了 usdz

let url = URL(string: "download usdz url")  
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!  
let destinationUrl = documentsUrl.appendingPathComponent(url!.lastPathComponent)  
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)  
var request = URLRequest(url: url!)  
request.httpMethod = "GET"  
let downloadTask = session.downloadTask(with: request, completionHandler: { (location:URL?, response:URLResponse?, error:Error?) -> Void in  
    let fileManager = FileManager.default  
    try! fileManager.moveItem(atPath: location!.path, toPath: destinationUrl.path)  
    do {  
        let testEntity = try Entity.load(contentsOf: destinationUrl) // Error  
    }  
    catch {  
        print("\(error.localizedDescription)")  

    }  

})  

downloadTask.resume() 

但是此代码因以下原因而崩溃:

let testEntity = try Entity.load(contentsOf: destinationUrl)

每个人都有这个问题吗?

stack picture

1 个答案:

答案 0 :(得分:0)

此问题已解决。 让实体在主线程上调用。

let url = URL(string: "download usdz url")  
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!  
let destinationUrl = documentsUrl.appendingPathComponent(url!.lastPathComponent)  
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)  
var request = URLRequest(url: url!)  
request.httpMethod = "GET"  
let downloadTask = session.downloadTask(with: request, completionHandler: { (location:URL?, response:URLResponse?, error:Error?) -> Void in  
    let fileManager = FileManager.default
    if fileManager.fileExists(atPath: destinationUrl.path) {
        try! fileManager.removeItem(atPath: destinationUrl.path)
    }  
    try! fileManager.moveItem(atPath: location!.path, toPath: destinationUrl.path)  
    DispatchQueue.main.async { 
        do {
            let object = try Entity.load(contentsOf: destinationUrl) // It is work
            let anchor = AnchorEntity(world: [0, 0, 0])
            anchor.addChild(object)
            self.arView.scene.addAnchor(anchor)
        }
        catch {
            print("Fail load entity: \(error.localizedDescription)")
        }
    }
})  
downloadTask.resume() 

感谢BlackMirrorz