swift - iOS VPN 连接阻止将 4G 连接切换到 WiFi 连接

标签 swift xcode vpn 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

此连接工作正常。如果我使用 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/

相关文章:

ios - libMobileGestalt MobileGestalt.c :890: MGIsDeviceOneOfType is not supported on this platform

ios - layer被constraints更新后调用@IBDesignable中的@IBInspectable set

linux - openconnect vpn 不会从 GUI 更改 resolv.conf 。软呢帽29

windows - Azure VPN 客户端未安装 P2S 连接配置文件

amazon-web-services - 如何从 VPN 访问 AWS ElastiCache (Redis)

ios - 检测滚动控件

arrays - Swift - 将结构数组传递给另一个结构的初始化

ios - 在 CCSprite 上检测触摸

ios - 键盘来时,如何设置UITextView中的文本字段上下移动?

iOS - Xcode 错误 : cannot attach to process due to System Integrity Protection