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。

我该如何解决这个问题?

4

1 回答 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
                }
            }
       }
}
于 2017-05-25T11:27:02.827 回答