iOS VPN连接会阻止切换4G到WiFi连接

13

我正在使用下面的按需连接规则,在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,则手机无法连接到WiFi,直到我手动从VPN断开连接。我认为,活跃的VPN连接会阻止从4G切换到WiFi。

我该如何解决这个问题?


在设置中打开 Wi-Fi 并点击您的网络名称会发生什么事? - Coder-256
1个回答

6

在扩展中,为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
                }
            }
       }
}

你好Roee84,你能给我一个关于这个的示例代码吗? - mTuran
@Roee84 除此之外,我还需要考虑其他方面才能保持 VPN 的持续连接吗?因为我发现它们有时会断开。谢谢 - Ricardo
1
@Ricardo,问题中的示例应该足以实现“始终连接”,例如: let connectRule = NEOnDemandRuleConnect() connectRule.interfaceTypeMatch = .any vpnManager.onDemandRules = [connectRule] vpnManager.isOnDemandEnabled = true - Witterquick
@Roee84 谢谢。看起来它有效了,现在我一直看到VPN图标,即使我重新启动了iPhone。我现在遇到的问题是,在使用几个小时或更改WiFi到3G等情况后,有时我会在控制台中看到这个错误:“error 21:19:25.226644 +0100 Domain Checker Extension __nw_socket_service_writes_block_invoke sendmsg(fd 5, 40 bytes): [51] Network is unreachable”,然后它就无法工作,直到我手动重启。有什么想法吗?我应该使用KVO应用于defaultPath来解决这个问题吗?非常感谢。 - Ricardo
不知道这个错误是什么,但尝试使用默认路径来检测这些更改,也许可以解决你的问题。 - Witterquick

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接