Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -91,4 +91,4 @@ fun HashScreen() {
)
}
}
}
}
3 changes: 2 additions & 1 deletion hello-swift-java/hashing-lib/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ let package = Package(
.library(
name: "SwiftHashing",
type: .dynamic,
targets: ["SwiftHashing"])
targets: ["SwiftHashing"]
)
],
dependencies: [
.package(url: "https://github.com/swiftlang/swift-java", branch: "main"),
Expand Down
5 changes: 5 additions & 0 deletions settings.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ project(":hello-swift-java-hashing-lib").projectDir = file("hello-swift-java/has
include(":hello-swift-java-hashing-app")
project(":hello-swift-java-hashing-app").projectDir = file("hello-swift-java/hashing-app")

include(":swift-java-weather-app-weather-lib")
project(":swift-java-weather-app-weather-lib").projectDir = file("swift-java-weather-app/weather-lib")
include(":swift-java-weather-app-weather-app")
project(":swift-java-weather-app-weather-app").projectDir = file("swift-java-weather-app/weather-app")

// raw-jni examples
include(":hello-swift-raw-jni")
include(":hello-swift-raw-jni-callback")
Expand Down
41 changes: 41 additions & 0 deletions swift-java-weather-app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
.DS_STORE

# Swift
.build/
.swiftpm/
Package.resolved

# Gradle files
.gradle/
build/

# Local configuration file (sdk path, etc)
local.properties

# Log/OS Files
*.log

# Android Studio generated files and folders
captures/
.externalNativeBuild/
.cxx/
*.aab
*.apk
output-metadata.json

# IntelliJ
*.iml
.idea/
misc.xml
deploymentTargetDropDown.xml
render.experimental.xml

# Keystore files
*.jks
*.keystore

# Google Services (e.g. APIs or Firebase)
google-services.json

# Android Profiling
*.hprof
95 changes: 95 additions & 0 deletions swift-java-weather-app/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# swift-java on Android

This example contains a sample Android application that demonstrates how to call Swift code from an Android app.
It shows you how to call `async` Swift functions from Kotlin/Java and also how it is possible
to implement a Swift `protocol` using a Java class and pass that back to Swift.

The example consists of an Android application (`weather-app`) and a Swift library (`weather-lib`) that fetches the weather for the current location. The Swift library uses [swift-java](https://github.com/swiftlang/swift-java) and the new JNI mode to **automatically generate Java wrappers** for calling into the Swift library.

![IDE Screenshot](resources/example.png)

## Overview

The project is structured into two main parts:
### **`weather-lib`**:
A Swift package that uses `swift-openapi-generator` to call the [Open-Meteo Weather API](https://open-meteo.com/). It is configured with a Gradle build script (`build.gradle`). This module utilizes the [swift-java](https://github.com/swiftlang/swift-java) project to create the necessary JNI bindings.

The Swift library exposes a Swift `protocol` named `LocationFetcher`, which is used by `WeatherClient` to
retrieve the current user location. This is a traditional API design in Swift, and allows any consumers
of the library to provide their own mechanism of retrieving the location. For iOS, this could mean using `CLLocationManager`.

`swift-java` allows us to implement the `LocationFetcher` protocol using a Java class,
and therefore use Android APIs to retrieve the user location and pass that back to Swift.
This is implemented in the `LocationService` class.

After fetching the user location, the `WeatherClient` will fetch the weather
using the automatically generated OpenAPI bindings. This method is marked as `async`
and we can easily call that from Java/Kotlin, where it will return a [CompletableFuture](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html)

### **`weather-app`**:
A standard Android application written in Kotlin using Jetpack Compose.

## Prerequisites

Before you can build and run this project, you need to have the following installed:

* **Java Development Kit (JDK)**: This example requires the use of JDK 25. This is only necessary to locally publish the swift-java dependencies, and will not be required in the future. To simplify the build steps, we recommend installing JDK 25 and following all the steps below using the same JDK. Ensure the `JAVA_HOME` environment variable is set to your JDK installation path.
* **Swiftly**: You need to install [Swiftly](https://www.swift.org/install/) to download the latest open-source Swift toolchain
* **Swift SDK for Android**: You need to install the [Swift SDK for Android](https://swift.org/install)

## Setup and Configuration

### Prepare Swift Android SDK and matching Swift

Currently, these examples utilize very recent nightly Swift Android SDK versions.

You can follow [these instructions](https://www.swift.org/documentation/articles/swift-sdk-for-android-getting-started.html) to install an appropriate Swift SDK for Android.

### Publish `swift-java` packages locally
As the `swift-java` project does not yet publish the necessary Java packages needed at runtime, we need to do it ourselves, by performing the following steps:

> Note: This step will not be necessary once swift-java publishes releases.

In order to publish all artifacts from this library, you must use JDK 25, because some parts of swift-java are built for the most recent Java versions. You will not have to use JDK 25 for the rest of the development process.
A simple way to install and manage local Java installations is [sdkman](https://sdkman.io):

> Note: You will _not_ have to use most recent Java versions for your Android app, and the example currently targets Java language version 11.

Here's how to install `sdkman`:
```bash
curl -s "https://get.sdkman.io" | bash
```
Now restart the terminal so that the `sdk` utility is added to your path, and then set JDK 25 as your current Java install.

```bash
sdk install java 25.0.1-amzn --use # only in order to publish swift-java artifacts locally
export JAVA_HOME="${HOME}/.sdkman/candidates/java/current"
```

Next, let's prepare and publish the swift-java support libraries:

1. Enter the `hashing-lib` directory
```bash
cd weather-lib
```
2. Resolve Swift Packages
```bash
swift package resolve
```
3. Publish the `swift-java` packages to local Maven repo
```bash
./.build/checkouts/swift-java/gradlew --project-dir .build/checkouts/swift-java :SwiftKitCore:publishToMavenLocal
```

## Running the example

1. Open the `swift-android-examples` project in Android Studio.

2. Select the `weather-app` Gradle target.

3. Run the app on an Android emulator or a physical device.

4. Press the "Fetch Weather" button.



Binary file added swift-java-weather-app/resources/example.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions swift-java-weather-app/weather-app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
63 changes: 63 additions & 0 deletions swift-java-weather-app/weather-app/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
}

android {
namespace = "com.example.weatherapp"
compileSdk = 36

defaultConfig {
applicationId = "com.example.weatherapp"
minSdk = 28
targetSdk = 36
versionCode = 1
versionName = "1.0"

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
buildFeatures {
compose = true
}
}

dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.activity.compose)
implementation("androidx.fragment:fragment-ktx:1.7.1")
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.ui)
implementation(libs.androidx.ui.graphics)
implementation(libs.androidx.ui.tooling.preview)
implementation(libs.androidx.material3)
implementation("com.google.android.gms:play-services-location:21.0.1")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.6.4")
implementation("org.swift.swiftkit:swiftkit-core:1.0-SNAPSHOT")
implementation(project(":swift-java-weather-app-weather-lib"))
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
androidTestImplementation(platform(libs.androidx.compose.bom))
androidTestImplementation(libs.androidx.ui.test.junit4)
debugImplementation(libs.androidx.ui.tooling)
debugImplementation(libs.androidx.ui.test.manifest)
}
21 changes: 21 additions & 0 deletions swift-java-weather-app/weather-app/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

package com.example.weatherapp

import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4

import org.junit.Test
import org.junit.runner.RunWith

import org.junit.Assert.*

/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.weatherapp", appContext.packageName)
}
}
30 changes: 30 additions & 0 deletions swift-java-weather-app/weather-app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.WeatherApp">
<activity
android:name=".MainActivity"
android:exported="true"
android:theme="@style/Theme.WeatherApp">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
Loading