Search code examples
ioscoreml

Is there a way to make CoreML model available for iOS11+ at source level


I have a CoreML model in my application.

At run time, the prediction feature should be disabled on iOS8-10 and active on iOS11.

To be able to compile, on all classes that use CoreML, I have added :

@available(iOS 11.0, *)

But the .mlmodel generates the Swift code at every rebuild discarding all annotations. And so creating compile errors like :

'MLModel' is only available on iOS 11.0 or newer

Is there a way in Xcode9 to make the mlmodel iOS11 only?

EDIT: This bug was fixed in XCode 9 beta 4. The workaround is not needed anymore.


Solution

  • Upd. 07/25/17: Apple just have introduced new API for compiling models on device. This means, that you can avoid steps 1-4 now.

    1. (optional) Switch to Xcode beta sudo xcode-select --switch /Applications/Xcode-beta.app/Contents/Developer.
    2. Compile your model: xcrun coremlcompiler compile /path/to/MyModel.mlmodel /path/to/output/folder.
    3. Put compiled model folder MyModel.mlmodelc into your app bundle.
    4. Add auto-generated swift model class (MyModel.swift) to your project manually and annotate it with @available(iOS 11.0, *). How to find model class
    5. Load and initialize your model:

      let path = Bundle.main.path(forResource: "MyModel", ofType: "mlmodelc")

      let url = URL(fileURLWithPath: path!)

      let model = try! MyModel(contentsOf: url)

    Warning: I haven't tried to upload such app to the AppStore. I’ve tried it on my test device, and it works, I’m just not sure if it continues working after releasing to the Appstore.