NetworkUtil for internet check in KMM
Asked Answered
H

1

8

how to check the internet availability in KMM (actual/expect)

ANDROID

actual class NetworkUtils actual constructor() {
    actual fun isNetworkAvailable(): Boolean {
        val connectivityManager =
            application.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = connectivityManager.activeNetworkInfo
        return networkInfo != null && networkInfo.isConnected
    }
}

COMMON

expect class NetworkUtils() {
    fun isNetworkAvailable(): Boolean
}

IOS


actual class NetworkUtils {
    actual fun isNetworkAvailable(): Boolean {
      //todo ?
        }

}

Harleyharli answered 29/4, 2023 at 11:0 Comment(0)
H
-1

in IOS

actual fun isNetworkAvailable(): Boolean {
        return runBlocking { isConnected() }
    }

    private suspend fun isConnected(): Boolean {
        return suspendCoroutine { continuation ->
            val url = NSURL(string = "https://www.google.com")
            val request = NSURLRequest.requestWithURL(url)

            val task = NSURLSession.sharedSession.dataTaskWithRequest(
                request = request,
                completionHandler = { _, _, error ->
                    val connected = error == null
                    continuation.resume(connected)
                }
            )

            task.resume()
        }
    }
Harleyharli answered 21/2 at 13:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.