-
Notifications
You must be signed in to change notification settings - Fork 23
add weather app example #25
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 11 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
f7e9e1d
weather app
madsodgaard 855efd0
working example
madsodgaard 29ef639
cleanup
madsodgaard d7704fb
use upstream
madsodgaard 7da7481
cleanup
madsodgaard 602c8e1
typo
madsodgaard f6c9b7c
Update MainActivity.kt to put back newline
finagolfin 5015b87
Update README.md with few tweaks
finagolfin f6dc80f
Merge remote-tracking branch 'origin/main' into weather-example
madsodgaard 64cb889
PR updates
madsodgaard 2093e82
image
madsodgaard 1691f81
fix link
madsodgaard File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. | ||
|
|
||
|  | ||
|
|
||
| ## 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. | ||
finagolfin marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| 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 a 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. | ||
|
|
||
|
|
||
|
|
||
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| /build |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
36 changes: 36 additions & 0 deletions
36
...er-app/weather-app/src/androidTest/java/com/example/weatherapp/ExampleInstrumentedTest.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
30
swift-java-weather-app/weather-app/src/main/AndroidManifest.xml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> |
93 changes: 93 additions & 0 deletions
93
swift-java-weather-app/weather-app/src/main/java/com/example/weatherapp/MainActivity.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| //===----------------------------------------------------------------------===// | ||
| // | ||
| // 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 android.Manifest | ||
| import android.os.Bundle | ||
| import androidx.activity.ComponentActivity | ||
| import androidx.activity.compose.setContent | ||
| import androidx.activity.enableEdgeToEdge | ||
| import androidx.activity.result.contract.ActivityResultContracts | ||
| import androidx.activity.viewModels | ||
| import androidx.compose.foundation.layout.Arrangement | ||
| import androidx.compose.foundation.layout.Column | ||
| import androidx.compose.foundation.layout.fillMaxSize | ||
| import androidx.compose.foundation.layout.padding | ||
| import androidx.compose.material3.Button | ||
| import androidx.compose.material3.MaterialTheme | ||
| import androidx.compose.material3.Surface | ||
| import androidx.compose.material3.Text | ||
| import androidx.compose.runtime.Composable | ||
| import androidx.compose.runtime.collectAsState | ||
| import androidx.compose.ui.Modifier | ||
| import androidx.compose.ui.unit.dp | ||
| import com.example.weatherapp.ui.theme.WeatherAppTheme | ||
| import com.example.weatherapp.viewmodel.WeatherViewModel | ||
|
|
||
| class MainActivity : ComponentActivity() { | ||
|
|
||
| private val viewModel: WeatherViewModel by viewModels() | ||
|
|
||
| private val requestPermissionLauncher = | ||
| registerForActivityResult( | ||
| ActivityResultContracts.RequestPermission() | ||
| ) { isGranted: Boolean -> | ||
| if (isGranted) { | ||
| viewModel.fetchWeather() | ||
| } | ||
| } | ||
|
|
||
| override fun onCreate(savedInstanceState: Bundle?) { | ||
| super.onCreate(savedInstanceState) | ||
| enableEdgeToEdge() | ||
| setContent { | ||
| WeatherAppTheme { | ||
| Surface( | ||
| modifier = Modifier.fillMaxSize().padding(top = 64.dp), | ||
| color = MaterialTheme.colorScheme.background | ||
| ) { | ||
| WeatherScreen(viewModel) { | ||
| requestPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION) | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| @Composable | ||
| fun WeatherScreen(viewModel: WeatherViewModel, onFetchWeatherClick: () -> Unit) { | ||
| val weatherData = viewModel.weatherData.collectAsState().value | ||
| val error = viewModel.error.collectAsState().value | ||
|
|
||
| Column( | ||
| modifier = Modifier | ||
| .fillMaxSize() | ||
| .padding(32.dp), | ||
| verticalArrangement = Arrangement.spacedBy(12.dp) | ||
| ) { | ||
| Button(onClick = onFetchWeatherClick) { | ||
| Text("Fetch Weather") | ||
| } | ||
|
|
||
| weatherData?.let { | ||
| Text("Temperature: ${it.temperature}°C") | ||
| Text("Wind Speed: ${it.windSpeed} km/h") | ||
| Text("Wind Direction: ${it.windDirection}°") | ||
| } | ||
|
|
||
| error?.let { | ||
| Text("Error: $it", color = MaterialTheme.colorScheme.error) | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.