I had developed an app required connected VPN to see the app content. My problem now, whenever user forgot to turn on VPN I need to show user alert box that remind user to connect to VPN to see the content once app opened (I think i need to implement this function in AppDelegate). How can I achieve this kind of situation? . Thank you in advance.
Asked
Active
Viewed 3,700 times
3 Answers
3
I wrote a little helper to detect what you're looking for. This is the snippet:
struct VpnChecker {
private static let vpnProtocolsKeysIdentifiers = [
"tap", "tun", "ppp", "ipsec", "utun"
]
static func isVpnActive() -> Bool {
guard let cfDict = CFNetworkCopySystemProxySettings() else { return false }
let nsDict = cfDict.takeRetainedValue() as NSDictionary
guard let keys = nsDict["__SCOPED__"] as? NSDictionary,
let allKeys = keys.allKeys as? [String] else { return false }
// Checking for tunneling protocols in the keys
for key in allKeys {
for protocolId in vpnProtocolsKeysIdentifiers
where key.starts(with: protocolId) {
// I use start(with:), so I can cover also `ipsec4`, `ppp0`, `utun0` etc...
return true
}
}
return false
}
}
Usage: VpnChecker.isVpnActive()
I also wrote a little blog post about it here

Alessandro Francucci
- 1,528
- 17
- 25
2
You're trying to connect to a specific site or IP address via the VPN, right? You can simply use Reachability to detect whether the IP address is reachable, and Apple sample code can be found here.
More information can be seen in these related questions.

Community
- 1
- 1

Michael Dautermann
- 88,797
- 17
- 166
- 215
-
1"You can simply use Reachability to detect whether the IP address is reachable" - no, you can't. Apple's host reachability doesn't actually test reaching the IP, it only tests the first hop (e.g. to local router). It's hopelessly misnamed. – occulus Aug 21 '17 at 14:47
2
To check if the connection goes through VPN implement this code and call it everytime the user use the app so this must be handled in
func applicationDidBecomeActive(_ application: UIApplication) { }
or
func applicationWillEnterForeground(_ application: UIApplication) { }
func isVPNConnected() -> Bool {
let cfDict = CFNetworkCopySystemProxySettings()
let nsDict = cfDict!.takeRetainedValue() as NSDictionary
let keys = nsDict["__SCOPED__"] as! NSDictionary
for key: String in keys.allKeys as! [String] {
if (key == "tap" || key == "tun" || key == "ppp" || key == "ipsec" || key == "ipsec0" || key == "utun1" || key == "utun2") {
return true
}
}
return false
}

JhonnyTawk
- 834
- 11
- 23