-2

我在代码中通过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).

大家有这个问题吗?

堆栈图片

4

1 回答 1

3

这个问题就解决了。让实体调用主线程。

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

于 2019-12-09T03:23:41.137 回答