[kotlin] Jetpack Compose에서 현재 날씨 정보 표시하기

안녕하세요! 이번에는 Jetpack Compose와 OpenWeatherMap API를 사용하여 안드로이드 앱에서 현재 날씨 정보를 표시하는 방법에 대해 알아보겠습니다.

필요한 라이브러리 추가

먼저, build.gradle 파일에 OpenWeatherMap API를 사용하기 위한 Retrofit과 Gson 라이브러리를 추가합니다.

dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}

API 요청 및 응답 모델 생성

다음으로, OpenWeatherMap API를 요청하고 응답을 처리하기 위한 모델을 생성합니다.

data class WeatherResponse(
    val main: Main,
    val weather: List<Weather>
)

data class Main(
    val temp: Double,
    val humidity: Int
)

data class Weather(
    val main: String,
    val description: String
)

interface WeatherService {
    @GET("weather")
    suspend fun getCurrentWeather(
        @Query("q") location: String,
        @Query("appid") apiKey: String
    ): WeatherResponse
}

Composable 함수 작성

이제 Jetpack Compose를 사용하여 현재 날씨 정보를 표시하는 Composable 함수를 작성합니다.

@Composable
fun CurrentWeather(weather: WeatherResponse) {
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(text = "현재 온도: ${weather.main.temp}°C")
        Text(text = "습도: ${weather.main.humidity}%")
        Text(text = "날씨: ${weather.weather[0].description}")
    }
}

ViewModel에서 데이터 가져오기

마지막으로, ViewModel을 사용하여 OpenWeatherMap API에서 현재 날씨 정보를 가져오고, UI에 표시합니다.

class WeatherViewModel : ViewModel() {
    private val apiService = Retrofit.Builder()
        .baseUrl("https://api.openweathermap.org/data/2.5/")
        .addConverterFactory(GsonConverterFactory.create())
        .build()
        .create(WeatherService::class.java)

    val currentWeather: MutableState<WeatherResponse?> = mutableStateOf(null)

    fun fetchCurrentWeather(location: String, apiKey: String) {
        viewModelScope.launch {
            try {
                val weather = apiService.getCurrentWeather(location, apiKey)
                currentWeather.value = weather
            } catch (e: Exception) {
                // Handle error
            }
        }
    }
}

이제 Jetpack Compose를 사용하여 안드로이드 앱에서 현재 날씨 정보를 표시하는 방법에 대해 알아보았습니다. OpenWeatherMap API를 통해 날씨 정보를 가져와서 UI에 표시하는 과정을 간략하게 살펴봤습니다. 본인의 앱에서 이를 활용하여 사용자에게 현재 날씨 정보를 제공해보세요.

참고문헌: