Type Method


Compiles a model on the device to update the model in your app.


class func compileModel(at modelURL: URL) throws -> URL



The local file path to your downloaded .mlmodel file.

Return Value

The local file path to the compiled model (the .mlmodelc file).


Use this method to compile a model for your app. The source .mlmodel file must be on the device. You can either use URLSession or CloudKit to download the model for your app. Pass the compiled model to init(contentsOf:) to create an instance of your model.

Listing 1

Compiling a model file and creating an MLModel instance from the compiled version.

let compiledUrl = try MLModel.compileModel(at: modelUrl)
let model = try MLModel(contentsOf: compiledUrl)

Compiling can be time consuming and shouldn't be done on the main thread.

Also, avoid repeating the download and compile processes when possible. The model is compiled to a temporary location. If the compiled model can be reused, move it to a permanent location, such as your app's support directory.

Listing 2

Copying the .mlmodelc file into your app's support directory.

let fileManager = FileManager.default
let appSupportDirectory = try! fileManager.url(for: .applicationSupportDirectory,
        in: .userDomainMask, appropriateFor: compiledUrl, create: true)
let permanentUrl = appSupportDirectory.appendingPathComponent(compiledUrl.lastPathComponent)
do {
    if fileManager.fileExists(atPath: permanentUrl.absoluteString) {
        _ = try fileManager.replaceItemAt(permanentUrl, withItemAt: compiledUrl)
    } else {
        try fileManager.copyItem(at: compiledUrl, to: permanentUrl)
} catch {
    print("Error during copy: \(error.localizedDescription)")