什么是VPN ?
个人理解是一个身份添加中心,比如,你在外面的时候需要连接公司内网,但是外网肯定是连不进去的,这个时候使用公司提供VPN,让你的外网有了一个内网的身份,这样你就可以进内网了。
虽然知道对代码没太大帮助,但是比不知道强,是吧?
先po一波参数解析,后面有使用代码贴图
虽然很多东西网上都能找到,但是本天才还是想用笔记的方式加深理解,顺便把一些东西整合一下,有助消化
俗话说,完事开头难,然后中间难,然后后面难,让我们开整
对于VPN iOS 9 出了一个很好用的框架 NetworkExtesion ,至于iOS9之前是用什么,我也不知道。
首先 导入系统框架 NetworkExtesion
定义一个VPN管理者,他后面会对VPN做很多羞羞的事情,所以很重要
@property (nonatomic,strong)NEVPNManager * vpnManager;
初始化一个管理者
self.vpnManager = [NEVPNManager sharedManager];
然后通过管理者的方法 loadFromPreferencesWithCompletionHandler 给管理者添加N多的VPN相关的信息
// VPN的配置
// NEVPNProtocolIKEv2 的官方说明
NEVPNProtocolIKEv2 *p = [[NEVPNProtocolIKEv2 alloc] init];
// 用户名
p.username = @"[Your username]";
// 从一个存储密码的钥匙链(keychain)获得的密码
p.passwordReference = [VPN user password from keychain];
// VPN的服务器地址
p.serverAddress = @"[Your server address]";
// VPN的认证方式
NEVPNIKEAuthenticationMethodNone:不要使用IPSec服务器进行身份验证。
NEVPNIKEAuthenticationMethodCertificate:使用证书和私钥作为身份验证凭据。
NEVPNIKEAuthenticationMethodSharedSecret:使用共享密钥的身份验证凭据。
p.authenticationMethod = NEVPNIKEAuthenticationMethodSharedSecret;
// 预共享秘钥,和上面的密码一样,也是从那个钥匙链获得的
p.sharedSecretReference = [VPN server shared secret from keychain];
// VPN的本地标识
p.localIdentifier = @"[VPN local identifier]";
// VPN的远程标识
p.remoteIdentifier = @"[VPN remote identifier]";
// VPN立Flag了
A flag indicating if extended authentication will be negotiated.
This authentication is in addition to the IKE authentication used to authenticate the endpoints of the IKE session.
p.useExtendedAuthentication = YES;
// 设备进入睡眠时候是否需要断开SVN
p.disconnectOnSleep = NO;
//官方解释
A boolean used to toggle the Connect On Demand capability.
The default value of this property is NO.
self.vpnManager.onDemandEnabled = NO;
// 把设置的那一大堆VPN属性和VPN管理者绑定
[self.vpnManager setProtocolConfiguration:p];
// 给你的VPN取个好听的名字 小甜甜怎么样?
self.vpnManager.localizedDescription = @"YU";
// 设置管理者可以开始干活了
self.vpnManager.enabled = true;
// 保存VPN配置信息到系统偏好设置
[self.vpnManager saveToPreferencesWithCompletionHandler:^(NSError * _Nullable error) {}];
// 启动VPN
NSError * error = nil;
[self.vpnManager.connection startVPNTunnelAndReturnError:&error];
// 关闭VPN
[self.vpnManager.connection startVPNTunnelAndReturnError:&error];
然后这里还要啰嗦一句, 在VPN的使用过程中, 可以通过通知的方式去监听VPN的各种变化,至于怎么实现,你们自己看着办吧,
我去买几个橘子,你们在这看文章,不要动。
然后在网上收集资料的时候发现了一个无码的swift版,有兴趣的可以撸一下。
硬货补充 部分实际代码

.m内定义一些identifier,具体值根据实际情况来






网友评论