简体   繁体   中英

How to download USDZ by URLSession?

I download usdz by urlsession in my code:

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() 

but this code crash for:

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

Does everybody have this problem?

stack picture

This problem is solved. let entity call on the main thread.

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() 

Thanks BlackMirrorz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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