我正在尝试使用网络扩展启动 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()
}
}