我正在使用Network Extension框架进行配置并以编程方式连接VPN服务器。我可以启动和停止VPN。我编写了以下代码来在viewDidLoad中配置VPN。
NEVPNManager *manager = [NEVPNManager sharedManager];
[manager loadFromPreferencesWithCompletionHandler:^(NSError *error) {
if(manager.protocol == nil)
{
NSString *filePath = [[NSBundle bundleForClass:[self class]] pathForResource:@"VPNCert" ofType:@"p12"];
NSData *certData = [NSData dataWithContentsOfFile:filePath];
NSString *certPassword = @"password";
NSString *vpnUsername = @"username";
NSString *vpnPassword = @"password";
NSString *vpnUrl = @"VPN Server IP";
// This saves my credentials to the keychain and returns a persistent keychain reference
NSData *passRef = [self addVPNCredentialsToKeychain:vpnUsername withPassword:vpnPassword];
NEVPNProtocolIPSec *p = [[NEVPNProtocolIPSec alloc] init];
p.authenticationMethod = NEVPNIKEAuthenticationMethodCertificate;
p.serverAddress = vpnUrl;
p.username = vpnUsername;
p.passwordReference = passRef;
p.identityData = certData;
p.identityDataPassword = certPassword;
p.disconnectOnSleep = NO;
p.useExtendedAuthentication = YES;
manager.protocol = p;
manager.enabled = YES;
[manager setOnDemandEnabled:NO];
[manager setLocalizedDescription:@"VPN Network"];
[manager saveToPreferencesWithCompletionHandler:^(NSError *error) {
if(error)
{
NSLog(@"Load error: %@", error);
}
}];
}
}];
我还在按下按钮时编写了启动VPN的代码。
- (IBAction)buttonPressed:(id)sender {
NEVPNManager *manager = [NEVPNManager sharedManager];
[manager loadFromPreferencesWithCompletionHandler:^(NSError *error) {
if (!error)
{
NSError *startError = [[NSError alloc] init];
[[NEVPNManager sharedManager].connection startVPNTunnelAndReturnError:&startError];
}
}];
}
为我工作的案例。
问题是
如果我在wifi中连接VPN然后切换到移动数据,在这种情况下VPN正在停止。我希望VPN只有在用户停止VPN时才能停止。
配置VPN时是否缺少任何步骤,因为VPN正在停止?
先谢谢。
答案 0 :(得分:0)
您需要添加规则以保持连接的持久性。同时启用onDemand [manager setOnDemandEnabled:YES];
<强>夫特强>
let connectRule = NEOnDemandRuleConnect()
connectRule.interfaceTypeMatch = .any
let disconnectRule = NEOnDemandRuleDisconnect()
disconnectRule.probeURL = URL(string:VPNCredentialsModel.instance.vpnProbeURL()!)