This repository contains a sample Android application that demonstrates how to call Swift code from a Android app.
The example consists of an Android application (HashingApp) and a Swift library (hashing-lib) that performs a SHA256 hash on a given string.
The Swift library uses swift-java and the new JNI mode to automatically
generate Java wrappers for calling into the Swift library.
The project is structured into two main parts:
-
hashing-lib: A Swift package that usesswift-cryptoto provide a hashing function. It is configured with a Gradle build script (build.gradle) that compiles the Swift code into an Android Archive (.aar) file. This module utilizes the swift-java project to create the necessary JNI bindings. -
HashingApp: A standard Android application written in Kotlin using Jetpack Compose. It includes the.aarfile generated byhashing-libas a local dependency and calls the Swifthashfunction when the user presses a button.
Before you can build and run this project, you need to have the following installed:
- Java Development Kit (JDK): Ensure the
JAVA_HOMEenvironment variable is set to your JDK installation path. - Swift SDK for Android: You need to install the Swift Android SDK
As the swift-java project does not yet publish the neccessary Java packages needed at runtime, we need to do it ourself, by performing the following steps:
- Enter the
hashing-libdirectorycd hashing-lib - Resolve Swift Packages
swift package resolve
- Publish the
swift-javapackages to local Maven repo./.build/checkouts/swift-java/gradlew --project-dir .build/checkouts/swift-java publishToMavenLocal
The project must be built in two stages: first the Swift library, then the Android application.
-
Navigate to the
hashing-libdirectory:cd hashing-lib -
Run the Gradle assemble command. This will compile the Swift code for all supported Android ABIs (arm64-v8a, armeabi-v7a, x86_64), run the
jextractplugin, and package everything into an.aarfile../gradlew assembleRelease
-
After a successful build, the Android library will be located at
hashing-lib/build/outputs/aar/hashing-lib-release.aar.
-
Open the
HashingAppproject in Android Studio. -
Android Studio will automatically sync the Gradle project. The app is already configured to include the
.aarfile from thehashing-libbuild output directory. -
Run the app on an Android emulator or a physical device.
-
Enter any text into the text field and press the "Hash" button. The app will call the Swift
hashfunction, and the resulting SHA256 digest will be displayed on the screen.
