Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use NWPathMonitor rather than Reachability #7

Open
rocketraman opened this issue Aug 21, 2023 · 6 comments
Open

Use NWPathMonitor rather than Reachability #7

rocketraman opened this issue Aug 21, 2023 · 6 comments

Comments

@rocketraman
Copy link

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.

@ln-12
Copy link
Owner

ln-12 commented Aug 23, 2023

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

@rocketraman
Copy link
Author

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.

@Egi10
Copy link

Egi10 commented Jan 14, 2024

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

@ahmadmssm
Copy link

@rocketraman Would you provide a code snippet please ?

@rocketraman
Copy link
Author

rocketraman commented Feb 2, 2024

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

@ahmadmssm
Copy link

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/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants