简体   繁体   English

如何与扩展共享CoreML模型?

[英]How to share CoreML model with extension?

I am sharing CoreML model with app extension. 我正在与应用程序扩展共享CoreML模型。 Xcode generates swift code for the model. Xcode为模型生成快速代码。 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. 将模型放在框架的资源文件夹中,然后可以在框架的捆绑包上创建模型的路径或url。

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): 它从类的捆绑包创建模型url(请参阅生成的init方法):

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. 对于框架中的类, Bundle(for: MarsHabitatPricer.self)是框架的捆绑。 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. 还要注意,使用同样生成的init(contentsOf:) ,您可以从任何喜欢的人中加载模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM