multiplatform-connectivity-status
multiplatform-connectivity-status copied to clipboard
Use NWPathMonitor rather than Reachability
iOS 12+ has the NWPathMonitor class for doing this, which doesn't require the 3rd party custom Reachability pod.
This class is Swift-based and therefore isn't directly accessible via KMP, but the Objective-C APIs can be used instead. For example, nw_path_monitor_create and similar.
Thanks a lot for the hint! Currently, I don't have the time to look into it, but I would happily review any PRs :)
I'm just now getting this working in my app, and it seems to work well in my so far admittedly basic testing. If I get some free time I'll consider submitting a PR.
Thank you for the information, @rocketraman . I tried doing the same, and it worked well in my project.
@rocketraman Would you provide a code snippet please ?
@ahmadmssm I used something like this in my iosMain
:
import platform.Network.*
import platform.darwin.dispatch_get_main_queue
class PlatformNetworkStatusChecker: NetworkStatusChecker {
private val monitor = nw_path_monitor_create()
private var isNetworkAvailable = true
init {
nw_path_monitor_set_update_handler(monitor) { path ->
val pathStatus = nw_path_get_status(path)
logger.debug { "Network path status change: $pathStatus" }
isNetworkAvailable = pathStatus == nw_path_status_satisfied
}
logger.debug { "Requesting network connectivity callbacks from network path monitor" }
nw_path_monitor_set_queue(monitor, dispatch_get_main_queue())
nw_path_monitor_start(monitor)
}
override fun isNetworkAvailable(): Boolean = isNetworkAvailable
}
A better implementation would probably use a StateFlow
of the network status, so your UI can react to it as well, but that should be a pretty trivial change.
Here is a link in case someone wants the syntax, it is the same as objective C. https://msolarana.netlify.app/2018/08/04/monitoring-network-changes/