I am sharing CoreML model with app extension. Xcode generates swift code for the model. In order to use that code in extension, I had to include same model with app extension as well. Is there a way to include model only once in the app, and use in both app and extension?
You have to create a shared framework in your project, which is included by the app and the extension as well. You put the model in the resource folder of the framework, and you can create the path or url to the model over the framework's bundle.
EDIT: Your generated model should find the model data automatically, if you place the generated model class in the framework, too. It creates the model url from the bundle of the class (see the generated init
methods):
init(contentsOf url: URL) throws {
self.model = try MLModel(contentsOf: url)
}
convenience override init() {
let bundle = Bundle(for: MyModel.self)
let assetPath = bundle.url(forResource: "MyModel", withExtension:"mlmodelc")
try! self.init(contentsOf: assetPath!)
}
In the case of a class from a framework, Bundle(for: MarsHabitatPricer.self)
is the bundle of the framework. Your framework only needs to export the model's class so you can use it in the app and extension.
Also note that with the likewise generated init(contentsOf:)
, you can load your model from everywere you like.