我正在使用以下按需连接规则在 Swift 中创建一个 VPN 连接:
let config = NEVPNProtocolIPSec()
config.serverAddress = ""
config.username = ""
config.passwordReference = ""
config.authenticationMethod = .sharedSecret
config.sharedSecretReference = ""
config.useExtendedAuthentication = true
config.disconnectOnSleep = true
let connectRule = NEOnDemandRuleConnect()
connectRule.interfaceTypeMatch = .any
vpnManager.onDemandRules = [connectRule]
vpnManager.protocolConfiguration = config
vpnManager.localizedDescription = ""
vpnManager.isOnDemandEnabled = true
vpnManager.isEnabled = true
此连接工作正常。如果我使用 WiFi,它会在与 WiFi 断开连接后重新连接,反之亦然。如果我正在使用蜂窝连接并尝试激活 WiFi,在我手动将其与 VPN 断开连接之前,手机不会连接到 WiFi。我相信有效的 VPN 连接会阻止从 4G 切换到 WiFi。
我该如何解决这个问题?
最佳答案
在扩展中,为 defaultPath 添加一个观察者。然后当界面改变时会通知你,你就可以重新连接WIFI了
编辑:示例代码
//add observer
let options = NSKeyValueObservingOptions([.new, .old])
self.addObserver(self, forKeyPath: "defaultPath", options: options, context: nil)
//detect interface changes
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let keyPath = keyPath {
if keyPath == "defaultPath" {
let oldPath = change?[.oldKey] as! NWPath
let newPath = change?[.newKey] as! NWPath
//expensive is 3g, not expensive is wifi
if !oldPath.isEqual(to: newPath)) {
//disconnect the VPN, maybe with cancelTunnelWithError
}
}
}
}
关于swift - iOS VPN 连接阻止将 4G 连接切换到 WiFi 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44010819/