在Objective-C中检查VPN连接

时间:2018-11-05 23:19:21

标签: ios objective-c vpn nevpnmanager

我想检查VPN连接是否存在。 我在Swift中找到了代码,但无法在Objective-C中使用NEVPNStatus:

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")
  }
}

我正在为Objective-C使用以下代码:但是在某些中文网络设备中它不起作用。如果网络仍未使用vpn,他们将发送“ TUN”。

- (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 个答案:

答案 0 :(得分:0)

在ViewDidLoad中添加观察者以获取VPN状态。

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)
}