1

我正在尝试使用网络扩展启动 VPN 数据包隧道,但 vpn 总是卡在“正在连接”状态。但是,个人 VPN 确实使用这些相同的设置进行连接。调用 startVPNtunnel 后,PackTunnel 扩展函数被调用,但状态仍为 Connecting

// Hard code VPN configurations
let tunnelBundleId = "group.linkapp.PacketTunnel"
let host = "hide.me"
let serverAddress = "free-ca.hide.me"
let username = "wahwah"
let password = "123456"

var vpnManager: NETunnelProviderManager = NETunnelProviderManager()

private func initVPNTunnelProviderManager() {
    NETunnelProviderManager.loadAllFromPreferences { (savedManagers: [NETunnelProviderManager]?, error: Error?) in
        if let error = error {
            print(error)
        }
        if let savedManagers = savedManagers {
            if savedManagers.count > 0 {
                self.vpnManager = savedManagers[0]
            }
        }

        self.vpnManager.loadFromPreferences(completionHandler: { (error:Error?) in
            if let error = error {
                print(error)
            }

            let providerProtocol = NETunnelProviderProtocol()


            Keychain.set(self.username, value: self.password)
            let passwordRef = Keychain.persistentRef(self.username)
            if passwordRef == nil {
                print("Failed to query password persistent ref")
            }
            providerProtocol.username = self.username
            providerProtocol.passwordReference = passwordRef
            providerProtocol.serverAddress = self.serverAddress

            self.vpnManager.protocolConfiguration = providerProtocol
            self.vpnManager.localizedDescription = "NEPacketTunnelVPNDemoConfig"
            self.vpnManager.isEnabled = true


            if self.vpnManager.protocolConfiguration?.proxySettings == nil {
                self.vpnManager.protocolConfiguration?.proxySettings = NEProxySettings()
            }

            self.vpnManager.saveToPreferences(completionHandler: { (error:Error?) in
                if let error = error {
                    print(error)
                } else {
                    print("Save successfully")
                }
            })

        })
    }
}


@IBAction func connectAction(_ sender: Any) {

    print("Go!")

    self.vpnManager.loadFromPreferences { (error:Error?) in
        if let error = error {
            print(error)
        }
        if ((sender as AnyObject).title(for: .normal) == "Connect") {
            do {
                try self.vpnManager.connection.startVPNTunnel()
            } catch {
                print(error)
            }
        } else {
            self.vpnManager.connection.stopVPNTunnel()
        }
    }
4

1 回答 1

0

我不确定您所说的“个人 VPN 确实使用这些相同的设置进行连接”是什么意思

在这种情况下,如果您卡在 Connecting 状态。有两种最可能的可能性:

1)您的网络扩展没有调用完成处理程序

- (void)startTunnelWithOptions:(NSDictionary *)options completionHandler:(void (^)(NSError *))completionHandler

完成处理程序让操作系统知道隧道已启动

2) 您的应用未订阅NSNotification.Name.NEVPNStatusDidChange.. 结果 VPN 已启动,但应用程序端不知道

于 2017-05-26T18:58:19.030 回答