在网络从wifi切换到移动数据期间,VPN正在停止。 VPN在iOS中以编程方式连接

时间:2015-12-11 05:58:37

标签: ios iphone ios8 vpn nevpnmanager

我正在使用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];
                }
            }];
}

为我工作的案例。

  1. 如果我在移动数据中连接VPN并切换到wifi,这种情况下VPN不会断开连接。
  2. 如果我在移动数据中连接VPN并切换到wifi然后再返回移动数据VPN也无法断开连接。
  3. 问题是

    如果我在wifi中连接VPN然后切换到移动数据,在这种情况下VPN正在停止。我希望VPN只有在用户停止VPN时才能停止。

    配置VPN时是否缺少任何步骤,因为VPN正在停止?

    先谢谢。

1 个答案:

答案 0 :(得分:0)

您需要添加规则以保持连接的持久性。同时启用onDemand [manager setOnDemandEnabled:YES];

<强>夫特

    let connectRule = NEOnDemandRuleConnect()
    connectRule.interfaceTypeMatch = .any

    let disconnectRule = NEOnDemandRuleDisconnect()
    disconnectRule.probeURL = URL(string:VPNCredentialsModel.instance.vpnProbeURL()!)