Using Swift sources in an extension

Is subj possible, any ideas or experience?

As far as I understand, to achieve this I can try to add a build phase to the tools for the Swift sources to create the object files with swiftc. These Swift sources should be designed so that they are exposed to Objective C. Then I can use the headers generated by swiftc with -emit-objc-header in Objective C code and link these .o files into the extension static .a library file.

Does it sound like a plan? :slight_smile:

On the other hand, I checked the design of extension-admob and somehow id doesn’t require to rebuild the extension (and thus to create the object files and libs). Instead, the code of the extension is compiled with the rest of the app by XCode. I guess I could include a Swift code file and bridging header easier so that XCode takes care of it, but it’s beyond my knowledge (same as the extension rebuild process though), probably I should dig this way instead?..

@pozirk how does the admob extension work this way, man? :slight_smile:

I’m not really familiar with iOS development.

I took Admob extension over from @fbricker so for me it just worked already. :slight_smile:

But I think @MAJigsaw77 knows well the part you are asking about, because this where he did lots of improvements. You can find him on Discord or Github.

Thanks for the info, @pozirk! Will try to reach out

So I used a lame but fast way to execute the Swift code and pass the results to ObjC, I really don’t recommend following this, but if you need a quick workaround, this may do.

So.

  1. I added a .swift file to “Other Sources” in the XCode project (and auto-created the bridging header as prompted)

  2. Added the Swift code to a function that I defined in this file. The code used async call to retrieve the first app version that the user had.

    public func checkVersion() {
    . . .
    }
    
  3. In main.mm I imported the auto-created header, you can find the name of the header in Build Settings under:
    Swift Compiler - General - Generated Header Name
    Let’s say it was “app_name-Swift.h”, then the import is
    #import “app_name-Swift.h”

  4. In main.mm function SDL_main I called that function from Swift with
    app_name::checkVersion();

  5. In Swift I put the retrieved version (originalVersion variable) into UserDefaults with
    UserDefaults.standard.set(originalVersion, forKey: “installVersion”)

  6. You have to change the Swift/ObjC interoperability settings of XCode to C++ / Objective C++ to make it work! The settings are in Build Settings under:
    Swift Compiler - Language → C++ and Objective C interoperability
    Alternatively you can add the following to each target in the XCode project template:
    SWIFT_OBJC_INTEROP_MODE = objcxx;

  7. In my OpenFL Haxe code I used Mobileprefs extension to read from UserDefaults

And it worked

Then I prepared the template to add that swift file and replace main.mm not to do all this each rebuild.

2 Likes