无标题文章

无标题文章_第1张图片
QQ20160928-0.png
- (void)viewDidLoad {
    [super viewDidLoad];
    [self configVpnAndSavePreferences];
}

- (void)configVpnAndSavePreferences {
    NSMutableArray *rules = [[NSMutableArray alloc] init];
    NEOnDemandRuleConnect *connectRule = [NEOnDemandRuleConnect new];
    [rules addObject:connectRule];
    
    self.vpnManager = [NEVPNManager sharedManager];
    [[NEVPNManager sharedManager] setOnDemandEnabled:NO];
    self.vpnManager.enabled = YES;
    [self.vpnManager setOnDemandRules:rules];
    
    [self.vpnManager loadFromPreferencesWithCompletionHandler:^(NSError * _Nullable error) {
        NSLog(@"loadFromPreferencesWithCompletionHandler");
        
        NEVPNProtocolIPSec *protocolIPSec = (NEVPNProtocolIPSec *)self.vpnManager.protocol;
        if (!protocolIPSec) {
            protocolIPSec = [[NEVPNProtocolIPSec alloc] init];
        }
        protocolIPSec.username = @"Mr.x";
        
        protocolIPSec.serverAddress = @"VPN Address";;
        
        _vpnManager.localizedDescription = @"IPSec Demo";
        
        protocolIPSec.passwordReference = [self searchKeychainCopyMatching:@"VPN_PASSWORD"];;
        // PSK
        protocolIPSec.authenticationMethod = NEVPNIKEAuthenticationMethodSharedSecret;
        
        protocolIPSec.sharedSecretReference = [self searchKeychainCopyMatching:@"PSK"];
        
        protocolIPSec.useExtendedAuthentication = YES;
        
        protocolIPSec.disconnectOnSleep = NO;
        
        _vpnManager.protocol = protocolIPSec;
        
        [_vpnManager saveToPreferencesWithCompletionHandler:^(NSError * _Nullable error) {
            if (error) {
                NSLog(@"Save Error: %@",error);
            }else {
                NSLog(@"Save!!");
            }
        }];
    }];
}

- (IBAction)connectVPN:(id)sender {
    NSError *startError = nil;
    [self.vpnManager.connection startVPNTunnelAndReturnError:&startError];
    if(startError) {
        if (startError.code == 1) {
            [self configVpnAndSavePreferences];  // save again...
        }
    } else {
        NSLog(@"Connection established!");
    }
    NSLog(@"startVPNTunnel Error: %@",startError);
}

- (IBAction)stopCennectingVPN:(id)sender {
    [_vpnManager.connection stopVPNTunnel];
}

你可能感兴趣的:(无标题文章)