I’m working on an iOS app where I’m trying to implement a feature that detects when the currently connected wifi network has changed and executes some code in response to that change (nothing huge like updating a database or making api calls, just some quick local code).
I’ve looked at NWPathMonitor, which seems to accomplish this when the app is open in the foreground, but I’d like to have the same functionality when the app is in the background or suspended.
I’ve tried using BGTaskScheduler for this, but I don’t find it reliable enough to schedule my network ‘checks’ to really be usable. Sometimes when a task is scheduled, it doesn’t get run for example.
I’m aware of other background processing use-cases that Apple exposes, but I feel the functionality I’m aiming for doesn’t fit things like background push notifications, deferred code execution, or long running tasks for example.
Is there a reliable way to be sure that my code is ran when the active network changes?
2
Answers
In a word, no. As you already know (and it definitely sounds like you’ve done your homework on this), you can’t reliably run in the background — even an app that is permitted, for a special reason, to run continuously in the background, isn’t guaranteed of running all the time, and scheduled background tasks might never be run — and there is no API by which your sleeping app is going to be woken by the system because the wifi network has changed. Push notifications clearly don’t meet your case because the knowledge that the wifi has changed doesn’t come from your server, it comes from the user’s device, and there is, as I just said, nothing on the device that can notify you of the change.
On the other hand, if your app serves some other purpose, it can certainly check the wifi situation as soon as it comes to the front (whether from suspension or from a cold start), so maybe you can do without the background functionality altogether. After all, if the change in the wifi situation matters only to your app, then who cares whether it learns of the change only when it comes back to the front? It could be like people who think they want to run a timer in the background when all they really need is to look at the clock when the app is suspended and look at it again when the app comes to the front.
You can use libraries like @react-native-community/netinfo to check the Wi-Fi state when the app comes to the foreground. This won’t detect background changes, but it allows you to react to the current state.