Check VPN connection in Objective-C

1.5k views Asked by At

I wanted to check VPN connection is there or not. I found code in Swift but I can not use NEVPNStatus in Objective-C:

func checkNEStatus( status:NEVPNStatus ) {
    switch status {
    case NEVPNStatus.Invalid:
      print("NEVPNConnection: Invalid")
    case NEVPNStatus.Disconnected:
      print("NEVPNConnection: Disconnected")
    case NEVPNStatus.Connecting:
      print("NEVPNConnection: Connecting")
    case NEVPNStatus.Connected:
      print("NEVPNConnection: Connected")
    case NEVPNStatus.Reasserting:
      print("NEVPNConnection: Reasserting")
    case NEVPNStatus.Disconnecting:
      print("NEVPNConnection: Disconnecting")
  }
}

I am using below code for Objective-C: but it doesn't work in some of Chinese network device. They are sending "TUN" if the network is still not using vpn.

- (BOOL)isVPNConnected
{
    NSDictionary *dict = CFBridgingRelease(CFNetworkCopySystemProxySettings());
    NSArray *keys = [dict[@"__SCOPED__"]allKeys];
    NSLog(@"keys==>%@",keys);
    for (NSString *key in keys) {
        if ([key rangeOfString:@"tap"].location != NSNotFound ||
            [key rangeOfString:@"tun"].location != NSNotFound ||
            [key rangeOfString:@"ipsec"].location != NSNotFound ||
            [key rangeOfString:@"ppp"].location != NSNotFound){
            return YES;
        }
    }
    return NO;
}
1

There are 1 answers

0
munibsiddiqui On

Add observer in your ViewDidLoad to get the VPN Status.

self.vpnManager.loadFromPreferences { (error) in
          if error != nil {
            print(error.debugDescription)
          }
         else{
            print("No error from loading VPN viewDidLoad")
         }
     }

 notificationObserver = NSNotificationCenter.defaultCenter().addObserverForName(NEVPNStatusDidChangeNotification, object: nil , queue: nil) {
   notification in

   print("received NEVPNStatusDidChangeNotification")

   let nevpnconn = notification.object as! NEVPNConnection
   let status = nevpnconn.status
   self.checkNEStatus(status)
}