【问题标题】:iOS VPN Connection Blocks Switching 4G to WiFi ConnectioniOS VPN 连接阻止将 4G 切换到 WiFi 连接
【发布时间】:2017-10-16 02:06:25
【问题描述】:

我正在使用以下按需连接规则在 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 并点击您的网络名称会怎样?

标签: swift xcode vpn nevpnmanager


【解决方案1】:

在扩展中,为 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,你能给我这个示例代码吗?
  • @Roee84 除此之外,我是否必须考虑其他方面才能拥有始终连接的 VPN?因为我看到他们不时断开连接。谢谢
  • @Ricardo 问题中的示例对于“始终连接”来说应该足够了,例如: let connectRule = NEOnDemandRuleConnect() connectRule.interfaceTypeMatch = .any vpnManager.onDemandRules = [connectRule] vpnManager.isOnDemandEnabled =真的
  • @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] 网络无法访问”,直到我手动重新启动它才能再次工作。任何想法?我应该使用应用于 defaultPath 的 KVO 来解决这个问题。非常感谢。
  • 不知道这是什么错误,但尝试使用 defaultPath 来检测这些更改,也许它会解决您的问题
猜你喜欢
  • 1970-01-01
  • 2015-02-01
  • 1970-01-01
  • 2013-09-16
  • 1970-01-01
  • 2021-01-06
  • 2020-12-02
  • 2022-01-17
  • 1970-01-01
相关资源
最近更新 更多