Contents

Downloading and Compiling a Model on the User’s Device

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

Overview

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 A/B testing

  • 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 URLSession, CloudKit, or another networking toolkit. Then compile the model definition by calling compileModel(at:).

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

This creates a new, compiled model file with the same name as the model description but ending 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 later, reduce your 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 permanent location, replacing it if necessary.
_ = try fileManager.replaceItemAt(permanentURL,
                                  withItemAt: compiledModelURL)

See Also

App integration