iOS VPN连接模块将4G切换到WiFi连接

mTu*_*ran 13 vpn xcode swift nevpnmanager

我正在使用下面的随需连接规则在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
Run Code Online (Sandbox Code Playgroud)

这种连接工作正常.如果我使用WiFi,它会在断开WiFi连接后重新连接,但反之亦然.如果我正在使用蜂窝连接并尝试激活WiFi,则手机将无法连接至WiFi,直到我手动断开其与VPN的连接.我相信一个活跃的VPN连接阻止从4G切换到WiFi.

我该如何解决这个问题?

Roe*_*e84 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
                }
            }
       }
}
Run Code Online (Sandbox Code Playgroud)