Downloading and Compiling a Model on the User’s Device

Install Core ML models on the user’s device dynamically at runtime.


Download and compile models within your app as an alternative to bundling with the app. Scenarios where this is a practical approach include:

  • Reducing the app’s download size of your app on the App Store

  • Determining the right models for the user after installation, based on their location, specific interests, and so on

  • Providing model updates over the network

Download and Compile the Model in the Background

Download the model definition file (ending in .mlmodel) onto the user’s device by using NSURLSession, CloudKit, or another networking toolkit. Then compile the model definition by calling compileModelAtURL:error:.

let compiledModelURL = try MLModel.compileModel(at: modelDescriptionURL)

This creates a new, compiled model file with the same name as the model description but ends in .mlmodelc. Create a new MLModel instance by passing the compiled model URL to its initializer.

let model = try MLModel(contentsOf: compiledModelURL)

Model instances you create from model files you’ve downloaded have the same capabilities as those you create from model files that you bundle with your app.

Save Reusable Models to a Permanent Location

MLModel saves models it compiles to a temporary location. If your app can reuse the model at a later time, reduce your app’s resource consumption by saving the compiled model to a permanent location.

Build the URL to a permanent location that your app can access in the future, such as Application Support.

let fileManager = FileManager.default
let appSupportURL = fileManager.urls(for: .applicationSupportDirectory,
                                     in: .userDomainMask).first!

Create the URL for the permanent compiled model file.

let compiledModelName = compiledModelURL.lastPathComponentlet
permanentURL = appSupportURL.appendingPathComponent(compiledModelName)

Move or copy the file to its permanent location.

// Copy the file to the to the permanent location, replacing it if necessary.
_ = try fileManager.replaceItemAt(permanentURL,
                                  withItemAt: compiledModelURL)

See Also

Machine Learning Model


An encapsulation of all the details of your machine learning model.

Making Predictions with a Sequence of Inputs

Integrate a recurrent neural network model to process sequences of inputs.