利用NetworkExtension库配置VPN

时间:2023-03-09 21:57:40
利用NetworkExtension库配置VPN

VPN简单说就是连接局域网的一个通道。Ios8之后苹果增加了一个VPN的接口NEVPNManager,它可以方便的添加VPN连接。

首先在你的Xcode内,TARGETS->Capabilities->打开persion VPN

利用NetworkExtension库配置VPN

在项目中添加NetWorkExtension库

利用NetworkExtension库配置VPN

引入头文件<NetworkExtension/NEVPNManager.h>以后

//创建管理对象

NEVPNManager *vpnManager = [NEVPNManager sharedManager];

从设置里面加载VPN

//给VPN配置信息

[manager loadFromPreferencesWithCompletionHandler:^(NSError * _Nullable error) {

NEVPNProtocolIPSec *set =(NEVPNProtocolIPSec*) self.manager.protocolConfiguration;

if(!set)

{

set = [[NEVPNProtocolIPSec alloc]init];

}

set.username = @"username";//VPN用户名

set.passwordReference = [@"password" dataUsingEncoding:NSUTF8StringEncoding];//VPN密码

set.serverAddress = @"ip";//ip地址

set.sharedSecretReference = [@"SecretReference"  dataUsingEncoding:NSUTF8StringEncoding];

//            NEVPNIKEAuthenticationMethodCertificate:使用证书和私钥作为身份验证凭据。

//            NEVPNIKEAuthenticationMethodSharedSecret:使用共享密钥的身份验证凭据

set.authenticationMethod = NEVPNIKEAuthenticationMethodSharedSecret;

set.useExtendedAuthentication = YES;//这是一个标志指示如果扩展验证将协商

set.disconnectOnSleep = NO;//这个布尔表示是否VPN连接时,必须断开设备睡觉

self.manager.protocolConfiguration = set;

self.manager.localizedDescription = @"hrjd";//VPN的描述

[self.manager setOnDemandEnabled:YES];

[self.manager saveToPreferencesWithCompletionHandler:^(NSError * _Nullable error) {

NSError * error1 ;

//连接VPN

[manager.connection startVPNTunnelAndReturnError:&error1];

if (error) {

NSLog(@"VPN连接失败");

}else{

NSLog(@"VPN连接成功");

}

}];

}];

[vpnManager.connection stopVPNTunnel];

//断开VPN