Skip to content

Instantly share code, notes, and snippets.

@Joony
Last active April 13, 2023 11:46
Show Gist options
  • Save Joony/7f715c871f9a5439c27c48c8a6432262 to your computer and use it in GitHub Desktop.
Save Joony/7f715c871f9a5439c27c48c8a6432262 to your computer and use it in GitHub Desktop.
Download and compile an MLModel.
import CoreML
extension MLModel {
/**
Use the model: `let model = try MLModel(contentsOf: permanentURL)`
*/
func download(url: URL) async throws -> URL {
let request = URLRequest(url: url)
let (data, _) = try await URLSession.shared.data(from: url)
let tempUrl = try FileManager.default.url(
for: .cachesDirectory,
in: .userDomainMask,
appropriateFor: .temporaryDirectory,
create: true
)
.appendingPathComponent("temp.mlmodel")
try data.write(to: tempUrl)
let compiledModelUrl = try await MLModel.compileModel(at: tempUrl)
let permanentUrl = try FileManager.default.url(
for: .applicationSupportDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
)
.appendingPathComponent("mlmodels")
.appendingPathComponent(compiledModelUrl.lastPathComponent)
_ = try FileManager.default.replaceItemAt(permanentUrl, withItemAt: compiledModelUrl)
try FileManager.default.removeItem(at: tempUrl)
return permanentUrl
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment