title: Connect to VPN programmatically in iOS 8
body: <p>Since the release of iOS 8 beta, I found a Network Extension framework in its bundle which is going to let developers configure and connect to VPN servers programmatically and without any profile installation.</p>
  
  <p>The framework contains a major class called NEVPNManager. This class also has 3 main methods that let me save, load or remove VPN preferences. I’ve written a piece of code in viewDidLoad method as following:</p>
  
  <pre><code>NEVPNManager *manager = [NEVPNManager sharedManager];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(vpnConnectionStatusChanged) name:NEVPNStatusDidChangeNotification object:nil];
  [manager loadFromPreferencesWithCompletionHandler:^(NSError *error) {
      if(error) {
          NSLog(@"Load error: %@", error);
      }}];
  NEVPNProtocolIPSec *p = [[NEVPNProtocolIPSec alloc] init];
  p.username = @“[My username]”;
  p.passwordReference = [KeyChainAccess loadDataForServiceNamed:@"VIT"];
  p.serverAddress = @“[My Server Address]“;
  p.authenticationMethod = NEVPNIKEAuthenticationMethodCertificate;
  p.localIdentifier = @“[My Local identifier]”;
  p.remoteIdentifier = @“[My Remote identifier]”;
  p.useExtendedAuthentication = NO;
  p.identityData = [My VPN certification private key];
  p.disconnectOnSleep = NO;
  [manager setProtocol:p];
  [manager setOnDemandEnabled:NO];
  [manager setLocalizedDescription:@"VIT VPN"];
  NSArray *array = [NSArray new];
  [manager setOnDemandRules: array];
  NSLog(@"Connection desciption: %@", manager.localizedDescription);
  NSLog(@"VPN status:  %i", manager.connection.status);
  [manager saveToPreferencesWithCompletionHandler:^(NSError *error) {
     if(error) {
        NSLog(@"Save error: %@", error);
     }
  }];
  </code></pre>
  
  <p>I also placed a button in my view and set its TouchUpInside action to the method below:</p>
  
  <pre><code>- (IBAction)buttonPressed:(id)sender {
     NSError *startError;
     [[NEVPNManager sharedManager].connection startVPNTunnelAndReturnError:&amp;startError];
     if(startError) {
        NSLog(@"Start error: %@", startError.localizedDescription);
     }
  }
  </code></pre>
  
  <p>There are two problems here:</p>
  
  <p>1) When I try to save the preferences, the following error will be thrown:  Save error: Error Domain=NEVPNErrorDomain Code=4 "The operation couldn’t be completed. (NEVPNErrorDomain error 4.)” What is this error? How can I solve this issue?</p>
  
  <p>2) [[NEVPNManager sharedManager].connection startVPNTunnelAndReturnError:&amp;startError]; method doesn’t return any error when I call it but the connection status changes from Disconnected to Connecting for just a moment and then it gets back to Disconnected state.</p>
  
  <p>Any help will be appreciated :)</p>