diff --git a/hello-swift-java/hashing-app/src/main/java/com/example/hashingapp/MainActivity.kt b/hello-swift-java/hashing-app/src/main/java/com/example/hashingapp/MainActivity.kt index 24cd5c8..ca1db54 100644 --- a/hello-swift-java/hashing-app/src/main/java/com/example/hashingapp/MainActivity.kt +++ b/hello-swift-java/hashing-app/src/main/java/com/example/hashingapp/MainActivity.kt @@ -91,4 +91,4 @@ fun HashScreen() { ) } } -} \ No newline at end of file +} diff --git a/hello-swift-java/hashing-lib/Package.swift b/hello-swift-java/hashing-lib/Package.swift index 0295118..0b82eea 100644 --- a/hello-swift-java/hashing-lib/Package.swift +++ b/hello-swift-java/hashing-lib/Package.swift @@ -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"), diff --git a/settings.gradle.kts b/settings.gradle.kts index 0be2778..fbd42d8 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -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") diff --git a/swift-java-weather-app/.gitignore b/swift-java-weather-app/.gitignore new file mode 100644 index 0000000..6e582d1 --- /dev/null +++ b/swift-java-weather-app/.gitignore @@ -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 \ No newline at end of file diff --git a/swift-java-weather-app/README.md b/swift-java-weather-app/README.md new file mode 100644 index 0000000..1343467 --- /dev/null +++ b/swift-java-weather-app/README.md @@ -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. + + + diff --git a/swift-java-weather-app/resources/example.png b/swift-java-weather-app/resources/example.png new file mode 100644 index 0000000..8d0a239 Binary files /dev/null and b/swift-java-weather-app/resources/example.png differ diff --git a/swift-java-weather-app/weather-app/.gitignore b/swift-java-weather-app/weather-app/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/swift-java-weather-app/weather-app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/swift-java-weather-app/weather-app/build.gradle.kts b/swift-java-weather-app/weather-app/build.gradle.kts new file mode 100644 index 0000000..61d00b0 --- /dev/null +++ b/swift-java-weather-app/weather-app/build.gradle.kts @@ -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) +} diff --git a/swift-java-weather-app/weather-app/proguard-rules.pro b/swift-java-weather-app/weather-app/proguard-rules.pro new file mode 100644 index 0000000..481bb43 --- /dev/null +++ b/swift-java-weather-app/weather-app/proguard-rules.pro @@ -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 \ No newline at end of file diff --git a/swift-java-weather-app/weather-app/src/androidTest/java/com/example/weatherapp/ExampleInstrumentedTest.kt b/swift-java-weather-app/weather-app/src/androidTest/java/com/example/weatherapp/ExampleInstrumentedTest.kt new file mode 100644 index 0000000..94455b3 --- /dev/null +++ b/swift-java-weather-app/weather-app/src/androidTest/java/com/example/weatherapp/ExampleInstrumentedTest.kt @@ -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) + } +} \ No newline at end of file diff --git a/swift-java-weather-app/weather-app/src/main/AndroidManifest.xml b/swift-java-weather-app/weather-app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..0fa972c --- /dev/null +++ b/swift-java-weather-app/weather-app/src/main/AndroidManifest.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + diff --git a/swift-java-weather-app/weather-app/src/main/java/com/example/weatherapp/MainActivity.kt b/swift-java-weather-app/weather-app/src/main/java/com/example/weatherapp/MainActivity.kt new file mode 100644 index 0000000..c773b4d --- /dev/null +++ b/swift-java-weather-app/weather-app/src/main/java/com/example/weatherapp/MainActivity.kt @@ -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) + } + } +} \ No newline at end of file diff --git a/swift-java-weather-app/weather-app/src/main/java/com/example/weatherapp/services/LocationService.kt b/swift-java-weather-app/weather-app/src/main/java/com/example/weatherapp/services/LocationService.kt new file mode 100644 index 0000000..00b9b54 --- /dev/null +++ b/swift-java-weather-app/weather-app/src/main/java/com/example/weatherapp/services/LocationService.kt @@ -0,0 +1,55 @@ +//===----------------------------------------------------------------------===// +// +// 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.services + +import android.Manifest +import android.content.Context +import android.content.pm.PackageManager +import androidx.core.content.ContextCompat +import com.google.android.gms.location.FusedLocationProviderClient +import com.google.android.gms.location.LocationServices +import com.example.weatherlib.LocationFetcher +import com.example.weatherlib.Location +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.tasks.await +import org.swift.swiftkit.core.SwiftArena + +typealias AndroidLocation = android.location.Location + +class LocationService(private val context: Context) : LocationFetcher { + private val arena = SwiftArena.ofAuto() + + private val fusedLocationClient: FusedLocationProviderClient = + LocationServices.getFusedLocationProviderClient(context) + + override fun currentLocation(`swiftArena$`: SwiftArena?): Location { + val androidLocation: AndroidLocation? = if (ContextCompat.checkSelfPermission( + context, + Manifest.permission.ACCESS_FINE_LOCATION + ) == PackageManager.PERMISSION_GRANTED + ) { + runBlocking { + fusedLocationClient.lastLocation.await() + } + } else { + null + } + + if (androidLocation == null) { + throw IllegalStateException("Failed to retrieve location. Ensure location permissions are granted and location services are enabled.") + } + + val location = Location.init(androidLocation.latitude, androidLocation.longitude, arena); + return location + } +} diff --git a/swift-java-weather-app/weather-app/src/main/java/com/example/weatherapp/ui/theme/Color.kt b/swift-java-weather-app/weather-app/src/main/java/com/example/weatherapp/ui/theme/Color.kt new file mode 100644 index 0000000..f9c0931 --- /dev/null +++ b/swift-java-weather-app/weather-app/src/main/java/com/example/weatherapp/ui/theme/Color.kt @@ -0,0 +1,23 @@ +//===----------------------------------------------------------------------===// +// +// 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.ui.theme + +import androidx.compose.ui.graphics.Color + +val Purple80 = Color(0xFFD0BCFF) +val PurpleGrey80 = Color(0xFFCCC2DC) +val Pink80 = Color(0xFFEFB8C8) + +val Purple40 = Color(0xFF6650a4) +val PurpleGrey40 = Color(0xFF625b71) +val Pink40 = Color(0xFF7D5260) \ No newline at end of file diff --git a/swift-java-weather-app/weather-app/src/main/java/com/example/weatherapp/ui/theme/Theme.kt b/swift-java-weather-app/weather-app/src/main/java/com/example/weatherapp/ui/theme/Theme.kt new file mode 100644 index 0000000..61ed15c --- /dev/null +++ b/swift-java-weather-app/weather-app/src/main/java/com/example/weatherapp/ui/theme/Theme.kt @@ -0,0 +1,70 @@ +//===----------------------------------------------------------------------===// +// +// 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.ui.theme + +import android.app.Activity +import android.os.Build +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.dynamicDarkColorScheme +import androidx.compose.material3.dynamicLightColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.platform.LocalContext + +private val DarkColorScheme = darkColorScheme( + primary = Purple80, + secondary = PurpleGrey80, + tertiary = Pink80 +) + +private val LightColorScheme = lightColorScheme( + primary = Purple40, + secondary = PurpleGrey40, + tertiary = Pink40 + + /* Other default colors to override + background = Color(0xFFFFFBFE), + surface = Color(0xFFFFFBFE), + onPrimary = Color.White, + onSecondary = Color.White, + onTertiary = Color.White, + onBackground = Color(0xFF1C1B1F), + onSurface = Color(0xFF1C1B1F), + */ +) + +@Composable +fun WeatherAppTheme( + darkTheme: Boolean = isSystemInDarkTheme(), + // Dynamic color is available on Android 12+ + dynamicColor: Boolean = true, + content: @Composable () -> Unit +) { + val colorScheme = when { + dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { + val context = LocalContext.current + if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) + } + + darkTheme -> DarkColorScheme + else -> LightColorScheme + } + + MaterialTheme( + colorScheme = colorScheme, + typography = Typography, + content = content + ) +} \ No newline at end of file diff --git a/swift-java-weather-app/weather-app/src/main/java/com/example/weatherapp/ui/theme/Type.kt b/swift-java-weather-app/weather-app/src/main/java/com/example/weatherapp/ui/theme/Type.kt new file mode 100644 index 0000000..318c6f2 --- /dev/null +++ b/swift-java-weather-app/weather-app/src/main/java/com/example/weatherapp/ui/theme/Type.kt @@ -0,0 +1,46 @@ +//===----------------------------------------------------------------------===// +// +// 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.ui.theme + +import androidx.compose.material3.Typography +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.sp + +// Set of Material typography styles to start with +val Typography = Typography( + bodyLarge = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 16.sp, + lineHeight = 24.sp, + letterSpacing = 0.5.sp + ) + /* Other default text styles to override + titleLarge = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 22.sp, + lineHeight = 28.sp, + letterSpacing = 0.sp + ), + labelSmall = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Medium, + fontSize = 11.sp, + lineHeight = 16.sp, + letterSpacing = 0.5.sp + ) + */ +) \ No newline at end of file diff --git a/swift-java-weather-app/weather-app/src/main/java/com/example/weatherapp/viewmodel/WeatherViewModel.kt b/swift-java-weather-app/weather-app/src/main/java/com/example/weatherapp/viewmodel/WeatherViewModel.kt new file mode 100644 index 0000000..ec05e31 --- /dev/null +++ b/swift-java-weather-app/weather-app/src/main/java/com/example/weatherapp/viewmodel/WeatherViewModel.kt @@ -0,0 +1,50 @@ +//===----------------------------------------------------------------------===// +// +// 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.viewmodel + +import android.app.Application +import android.util.Log +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.application +import androidx.lifecycle.viewModelScope +import com.example.weatherapp.services.LocationService +import com.example.weatherlib.WeatherClient +import com.example.weatherlib.WeatherData +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.future.await +import kotlinx.coroutines.launch +import org.swift.swiftkit.core.SwiftArena + +class WeatherViewModel(application: Application) : AndroidViewModel(application) { + private val arena = SwiftArena.ofAuto() + + private val _weatherData = MutableStateFlow(null) + val weatherData = _weatherData.asStateFlow() + + private val _error = MutableStateFlow(null) + val error = _error.asStateFlow() + + fun fetchWeather() { + viewModelScope.launch { + try { + val locationService = LocationService(application) + val weatherClient = WeatherClient.init(locationService, arena) + val weather = weatherClient.getWeather(arena).await() + _weatherData.value = weather + } catch (e: Exception) { + _error.value = "An unexpected error occurred: ${e.message}" + } + } + } +} diff --git a/swift-java-weather-app/weather-app/src/main/res/drawable/ic_launcher_background.xml b/swift-java-weather-app/weather-app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..07d5da9 --- /dev/null +++ b/swift-java-weather-app/weather-app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/swift-java-weather-app/weather-app/src/main/res/drawable/ic_launcher_foreground.xml b/swift-java-weather-app/weather-app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..2b068d1 --- /dev/null +++ b/swift-java-weather-app/weather-app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/swift-java-weather-app/weather-app/src/main/res/mipmap-anydpi/ic_launcher.xml b/swift-java-weather-app/weather-app/src/main/res/mipmap-anydpi/ic_launcher.xml new file mode 100644 index 0000000..6f3b755 --- /dev/null +++ b/swift-java-weather-app/weather-app/src/main/res/mipmap-anydpi/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/swift-java-weather-app/weather-app/src/main/res/mipmap-anydpi/ic_launcher_round.xml b/swift-java-weather-app/weather-app/src/main/res/mipmap-anydpi/ic_launcher_round.xml new file mode 100644 index 0000000..6f3b755 --- /dev/null +++ b/swift-java-weather-app/weather-app/src/main/res/mipmap-anydpi/ic_launcher_round.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/swift-java-weather-app/weather-app/src/main/res/mipmap-hdpi/ic_launcher.webp b/swift-java-weather-app/weather-app/src/main/res/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 0000000..c209e78 Binary files /dev/null and b/swift-java-weather-app/weather-app/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/swift-java-weather-app/weather-app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/swift-java-weather-app/weather-app/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 0000000..b2dfe3d Binary files /dev/null and b/swift-java-weather-app/weather-app/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/swift-java-weather-app/weather-app/src/main/res/mipmap-mdpi/ic_launcher.webp b/swift-java-weather-app/weather-app/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 0000000..4f0f1d6 Binary files /dev/null and b/swift-java-weather-app/weather-app/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/swift-java-weather-app/weather-app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/swift-java-weather-app/weather-app/src/main/res/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 0000000..62b611d Binary files /dev/null and b/swift-java-weather-app/weather-app/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/swift-java-weather-app/weather-app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/swift-java-weather-app/weather-app/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 0000000..948a307 Binary files /dev/null and b/swift-java-weather-app/weather-app/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/swift-java-weather-app/weather-app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/swift-java-weather-app/weather-app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..1b9a695 Binary files /dev/null and b/swift-java-weather-app/weather-app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/swift-java-weather-app/weather-app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/swift-java-weather-app/weather-app/src/main/res/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 0000000..28d4b77 Binary files /dev/null and b/swift-java-weather-app/weather-app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/swift-java-weather-app/weather-app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/swift-java-weather-app/weather-app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..9287f50 Binary files /dev/null and b/swift-java-weather-app/weather-app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/swift-java-weather-app/weather-app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/swift-java-weather-app/weather-app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 0000000..aa7d642 Binary files /dev/null and b/swift-java-weather-app/weather-app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/swift-java-weather-app/weather-app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/swift-java-weather-app/weather-app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..9126ae3 Binary files /dev/null and b/swift-java-weather-app/weather-app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/swift-java-weather-app/weather-app/src/main/res/values/colors.xml b/swift-java-weather-app/weather-app/src/main/res/values/colors.xml new file mode 100644 index 0000000..f8c6127 --- /dev/null +++ b/swift-java-weather-app/weather-app/src/main/res/values/colors.xml @@ -0,0 +1,10 @@ + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + \ No newline at end of file diff --git a/swift-java-weather-app/weather-app/src/main/res/values/strings.xml b/swift-java-weather-app/weather-app/src/main/res/values/strings.xml new file mode 100644 index 0000000..00461f1 --- /dev/null +++ b/swift-java-weather-app/weather-app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + Weather App + \ No newline at end of file diff --git a/swift-java-weather-app/weather-app/src/main/res/values/themes.xml b/swift-java-weather-app/weather-app/src/main/res/values/themes.xml new file mode 100644 index 0000000..29b8bc1 --- /dev/null +++ b/swift-java-weather-app/weather-app/src/main/res/values/themes.xml @@ -0,0 +1,5 @@ + + + +