codenameone / CodenameOne

Cross-platform framework for building truly native mobile apps with Java or Kotlin. Write Once Run Anywhere support for iOS, Android, Desktop & Web.
https://www.codenameone.com/
Other
1.7k stars 403 forks source link

RFE: Support for Swift libraries? #3274

Open jsfan3 opened 3 years ago

jsfan3 commented 3 years ago

The fact that Codename One allows to create native interfaces with Objective-C is essential, but now all new libraries for iOS are written in Swift. This is starting to be a serious problem.

shannah commented 3 years ago

I agree. We should add support for Swift inside the native/ios directory.

Until that happens, you can use Swift libraries by creating a Swift framework and placing it in your native/ios directory zipped. E.g.

native/ios/MyFramework.framework.zip

Then you can call your framework's methods from Objective-C code using the usual Objective-C -> Swift interop mechanism.

You'll also need to add the following build hints:

ios.pods.build.CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES=YES
ios.pods.build.CLANG_ENABLE_MODULES=YES

If the Swift libraries you want to use are already set up to be usable from Objective-C (e.g. they've exported functions with @ObjC annotations), then you don't necessarily even need to create your own intermediary framework.. you can use them directly from your Objective-C code.

The webrtc cn1lib uses this approach because it uses a Swift library for some of the WebRTC stuff.

Improving Swift Integration

There are 2 levels of Swift integration that we could aim for to make things easier:

  1. The build server automatically packages .swift files as a framework so that you can place .swift files directly inside the native/ios directory. You still need an Objective-C file as the main native interface implementation, but can call the Swift classes from there.
  2. Remove the requirement of Objective-C entirely. Native interface can be defined purely in Swift. This would basically work by using the same technique as in "1" above, but the server would just automatically generate the needed bridging stubs so that the Swift native interface could work.
schreiby commented 2 years ago

Thank you for this guide.

Is there a way to use native Swift code in the native/ios directory instead of Objective-C?