Skip to content

Instantly share code, notes, and snippets.

@maxxfrazer
Last active August 16, 2022 20:21
Example of downloading a USDZ file from a remote URL synchronously
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