0

我想检查 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;
}
4

1 回答 1

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)
}
于 2018-11-19T05:11:51.543 回答