簡體   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