我正在使用下面的代码(兼容Swift 3和Swift 4)检查iOS设备上的VPN连接,该设备在iOS 12及更高版本中不起作用。如何检查iOS 12中的VPN连接
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") {
return true
}
}
return false
}
谢谢您的帮助。
答案 0 :(得分:2)
自iOS 12和iOS 13起,键列表已更改
已添加2个键
utun1和utun2
所以函数应该是:
static func isConnectedToVPN() -> 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
}
答案 1 :(得分:1)
尝试将密钥“ utun1”添加到您的支票中(或以“ utun”为前缀,后跟数字)。
for key: String in keys.allKeys as! [String] {
if (key == "tap" || key == "tun" || key == "ppp" || key == "ipsec" || key == "ipsec0" || key == "utun1") {
return true
}
}
return false
答案 2 :(得分:0)
就我而言,我收到了ipsec4
,但该应用程序无法识别VPN。
因此,我想出了一些不同的方法:
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
}
}
用法:VpnChecker.isVpnActive()
我还写了一篇有关here
的博客文章