/Download+Remote+USDZ.swift Secret
Last active
August 16, 2022 20:21
Example of downloading a USDZ file from a remote URL synchronously
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func downloadUSDZ(from url: String, to destination: URL) -> URL? { | |
guard let remoteURL = URL(string: url) else { | |
return nil | |
} | |
var semaphore = DispatchSemaphore(value: 0) | |
var request = URLRequest(url: remoteURL, timeoutInterval: 10) | |
request.httpMethod = "GET" | |
var downloadLocation: URL? | |
let task = URLSession.shared.downloadTask( | |
with: request | |
) { location, response, error in | |
defer { semaphore.signal() } | |
guard error == nil else { | |
return | |
} | |
let destinationUrl = destination.appendingPathComponent(remoteURL.lastPathComponent) | |
if FileManager.default.fileExists(atPath: destinationUrl.path) { | |
try! FileManager.default.removeItem(atPath: destinationUrl.path) | |
} | |
try! FileManager.default.moveItem(atPath: location!.path, toPath: destinationUrl.path) | |
downloadLocation = destinationUrl | |
} | |
task.resume() | |
semaphore.wait() | |
return downloadLocation | |
} | |
guard let downloadLocation = downloadUSDZ( | |
from: "https://developer.apple.com/augmented-reality/quick-look/models/stratocaster/fender_stratocaster.usdz", | |
to: docsURL | |
) else { | |
fatalError("could not download usdz") | |
} | |
let guitarEntity = try? Entity.load(contentsOf: downloadLocation) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment