multiplatform-connectivity-status icon indicating copy to clipboard operation
multiplatform-connectivity-status copied to clipboard

Use NWPathMonitor rather than Reachability

Open rocketraman opened this issue 1 year ago • 6 comments

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.

rocketraman avatar Aug 21 '23 21:08 rocketraman

Thanks a lot for the hint! Currently, I don't have the time to look into it, but I would happily review any PRs :)

ln-12 avatar Aug 23 '23 17:08 ln-12

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.

rocketraman avatar Aug 23 '23 17:08 rocketraman

Thank you for the information, @rocketraman . I tried doing the same, and it worked well in my project.

Egi10 avatar Jan 14 '24 04:01 Egi10

@rocketraman Would you provide a code snippet please ?

ahmadmssm avatar Feb 02 '24 15:02 ahmadmssm

@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.

rocketraman avatar Feb 02 '24 15:02 rocketraman

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/

ahmadmssm avatar Feb 02 '24 23:02 ahmadmssm