Detect Network Changes in Background (iOS)

1.8k Views Asked by At

I am trying to create a VPN app that notifies the user when the VPN is turned off manually in the Settings app. More generally, I want to be able to react when the network settings are changed. I have seen a lot of comments on StackOverflow regarding Reachability, Network, etc. but I can't find out whether I can check these things in the background. Would there be a way to do it by using "fetch" or "remote-notification". I have an app on my phone that gives me a notification if I turn off the VPN, so I know there's a way to do it, but I can't figure out how.

2

There are 2 best solutions below

2
On

This will work to monitor your internet status every 3 seconds:

import Cocoa
import Darwin
import Network

//DispatchQueue.global(qos: .userInitiated).async {
let monitor = NWPathMonitor()
let queue = DispatchQueue(label: "Monitor")
monitor.start(queue: queue)
var count = 10


while count >= 0 {
    
monitor.pathUpdateHandler = { path in
    
    if path.status == .satisfied {
        print("There is internet")
        
        if path.usesInterfaceType(.wifi) { print("wifi") }
        else if path.usesInterfaceType(.cellular) { print("wifi") }
        else if path.usesInterfaceType(.wiredEthernet) { print("wiredEthernet") }
        else if path.usesInterfaceType(.loopback) { print("loopback") }
        else if path.usesInterfaceType(.other) { print("other") }

        
    } else {
        print("No internet")
    }
    
}
   sleep(3)
   count = count - 1
}

monitor.cancel()
//}

This code returns every three seconds the internet status and the connection type. if you want this to run for ever, change the while count >= 0 to while true with DispatchQueue.global(qos: .userInitiated).async { or DispatchQueue.global(qos: .background).async { you can move the task to the background.
To continue run the code in background (when app is not present) follow along https://www.hackingwithswift.com/example-code/system/how-to-run-code-when-your-app-is-terminated .

Note: The Appstore will sometimes reject your app when using the reachability framework.

1
On

According to This Apple Developer Discussion:

The answer might be No. This Apple developer discussion might be answered by Apple staff.

There’s no mechanism for running code in the background on network changes. Most folks who need to do this sort of thing use the VPN On Demand architecture. VPN On Demand has an API, but that API directly maps to configuration profile properties and configuration profiles aren’t considered an API (meaning they’re supported by Apple Support, not by Developer Technical Support).