我想将 VPN 服务器与我的 iOS 应用程序连接。我无法与 VPN 服务器建立连接。我对此进行了很多搜索,但没有得到任何解决方案。
这是我的代码:
import UIKit
import NetworkExtension
import Security
class VPN
{
static let shared = VPN()
let vpnManager = NEVPNManager.shared()
private var vpnLoadHandler: (Error?) -> Void { return
{ (error:Error?) in
if ((error) != nil) {
print("Could not load VPN Configurations")
return;
}
let p = NEVPNProtocolIPSec()
p.username = UserDefaults.standard.string(forKey: "uname")
p.serverAddress = UserDefaults.standard.string(forKey: "server")
p.authenticationMethod = NEVPNIKEAuthenticationMethod.sharedSecret
p.passwordReference = UserDefaults.standard.string(forKey: "pwd")?.data(using: .utf8)!
p.useExtendedAuthentication = true
p.disconnectOnSleep = true
self.vpnManager.protocolConfiguration = p
self.vpnManager.localizedDescription = "Contensi"
self.vpnManager.isEnabled = true
self.vpnManager.saveToPreferences(completionHandler: nil)
}
}
private var vpnSaveHandler: (Error?) -> Void { return
{
(error:Error?) in
if (error != nil) {
print("Could not save VPN Configurations")
return
} else
{
do
{
try self.vpnManager.connection.startVPNTunnel()
} catch let error
{
print("Error starting VPN Connection \(error.localizedDescription)");
}
}
}
// self.vpnlock = false
}
public func connectVPN() {
do
{
try self.vpnManager.loadFromPreferences(completionHandler: self.vpnLoadHandler)
} catch let error
{
print("Could not start VPN Connection: \(error.localizedDescription)" )
}
}
public func disconnectVPN() ->Void {
vpnManager.connection.stopVPNTunnel()
}
class VPNViewController: UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
}
}