我找不到关于如何做到这一点的明确答案,所以这就是我创建这个帖子的原因。
我正在开发一个Swift应用程序(Swift 2),我想用一个函数连接VPN服务器。所以我想创建一个
func connect() {
//Handle the connection to the VPN
}
我从制作VPN的开发者那里收到了这个https://gist.github.com/matthijsotterloo/cedf256f7f1c2a9a8f624481b7083afd文件(当然我更换了证书,密钥,网址和登录信息。现在我的问题是如何在功能中连接到这个VPN服务器?我已经发现我必须使用NEVPNManager但我无法真正找到如何构建它。
希望有人可以帮助我。
谢谢!
答案 0 :(得分:5)
这有点令人困惑,但您使用所需参数设置了配置,然后将该配置保存到NEVPNManager。之后启动VPN隧道。
所以你会有类似的东西:
NEVPNManager.sharedManager().loadFromPreferencesWithCompletionHandler { error in
// setup the config:
let password = vpnAccount!.vpnPassword
let vpnhost = vpnAccount!.vpnHost
let p = NEVPNProtocolIKEv2()
p.username = username
p.localIdentifier = username
p.serverAddress = vpnhost
p.remoteIdentifier = vpnhost
p.authenticationMethod = .None
p.passwordReference = passwordRef
p.useExtendedAuthentication = true
p.serverCertificateIssuerCommonName = vpnhost
p.disconnectOnSleep = false
var rules = [NEOnDemandRule]()
let rule = NEOnDemandRuleConnect()
rule.interfaceTypeMatch = .Any
rules.append(rule)
NEVPNManager.sharedManager().localizedDescription = "My VPN"
NEVPNManager.sharedManager().protocolConfiguration = p
NEVPNManager.sharedManager().onDemandRules = rules
NEVPNManager.sharedManager().onDemandEnabled = true
NEVPNManager.sharedManager().enabled = true
NEVPNManager.sharedManager().saveToPreferencesWithCompletionHandler { error in
guard error == nil else {
print("NEVPNManager.saveToPreferencesWithCompletionHandler failed: \(error!.localizedDescription)")
return
}
VPNManager.sharedManager.startVPNTunnel()
}
}
正确嵌套完成处理程序也非常明显但很重要:
loadFromPreferencesWithCompletionHandler{
...
saveToPreferencesWithCompletionHandler{
startVPNTunnel
}
}
passwordRef是:
let password = vpnAccount!.vpnPassword
vpnAccount!.setPersistenRef(username, password: password!)
let passwordRef = vpnAccount!.persistentRef
和vpnAccount.persistentRef是:
class func persistentRef(_ key: String) -> Data? {
let query: [AnyHashable: Any] = [
kSecClass as AnyHashable: kSecClassGenericPassword,
kSecAttrGeneric as AnyHashable: key,
kSecAttrAccount as AnyHashable: key,
kSecAttrAccessible as AnyHashable: kSecAttrAccessibleAlways,
kSecMatchLimit as AnyHashable: kSecMatchLimitOne,
kSecAttrService as AnyHashable: Bundle.main.bundleIdentifier!,
kSecReturnPersistentRef as AnyHashable: kCFBooleanTrue
]
var secItem: AnyObject?
let result = SecItemCopyMatching(query as CFDictionary, &secItem)
if result != errSecSuccess {
return nil
}
return secItem as? Data
}
我不记得细节,但似乎记得以上内容对于创建NEVPNManager正在寻找的引用非常重要。