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.
Detect Network Changes in Background (iOS)
1.9k Views Asked by aequinox At
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.
According to This Apple Developer Discussion:
The answer might be No. This Apple developer discussion might be answered by Apple staff.