繁体   English   中英

如何通过 URLSession 下载 USDZ?

[英]How to download USDZ by URLSession?

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

大家有这个问题吗?

堆叠图片

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM