Ad

Flutter Plugin: Share Code Between IOS And MacOS

- 1 answer

I have a common dir at the root dir of the plugin that holds code that should be shared by both iOS and MacOS. I changed the source_files in the .podspec files of both to point to the common dir: s.source_files = '../common/Classes/**/*', but now when I build either of the ios/macos examples, build fails with error that it can’t find the plugin import.

/Flutter/GeneratedPluginRegistrant.swift:8:8: error: no such module 'plugin_name'

Is this the right way to share code between iOS and Macos? How do I fix this?

Ad

Answer

It appears that it wasn't the right way to share code between iOS and MacOS. Instead what I should've done is:

  1. Keep .podspec files unchanged.
  2. Create a directory at the root of the plugin codebase called apple (the name doesn't matter).
  3. Move the common code to the directory created in step 2.
  4. Create symlinks to each common code file from ios/Classes and macos/Classes (assuming in corresponding directory):
ln -s ../../apple/Classes/SwiftSomePlugin.swift SwiftSomePlugin.swift

In my case I had only one file, but if you have more files, you need to create symlink per each file.

The end result should look like this:

├── apple
│   └── Classes
│       └── SwiftSomePlugin.swift
├── ios
│   ├── Assets
│   ├── Classes
│   │   ├── SomePlugin.h
│   │   ├── SomePlugin.m
│   │   └── SwiftSomePlugin.swift -> ../../apple/Classes/SwiftSomePlugin.swift
│   └── some.podspec
├── macos
│   ├── Classes
│   │   └── SwiftSomePlugin.swift -> ../../apple/Classes/SwiftSomePlugin.swift
│   └── some.podspec

Now run the build and it should succeed.

Ad
source: stackoverflow.com
Ad