重新启动应用后,NEVPNManager检查是否已连接?

时间:2016-08-20 16:53:30

标签: ios networkextension nevpnmanager

我使用NetworkExtension框架编码 VPN 工具。我可以通过NEVPNManager.sharedManager连接 IPSec ,并在 VPN 连接状态发生变化时抓取通知。但是当我杀死应用程序并重新打开它时,NEVPNManager.Connect.Status总是为零,而不是手段无法显示正确的连接状态。怎么解决?

2 个答案:

答案 0 :(得分:10)

William Sterling 评论确实有意义,&它对我有用,

在为BW Manager对象NEVPNStatusDidChange加载首选项添加观察者之前,如下所述

override func viewDidLoad() {

        super.viewDidLoad()

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

        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.VPNStatusDidChange(_:)), name: NSNotification.Name.NEVPNStatusDidChange, object: nil)

     }

答案 1 :(得分:2)

试试这个:

func viewDidLoad() {
    // Register to be notified of changes in the status. These notifications only work when app is in foreground.
    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)
    }
}



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

在运行已连接VPN的应用程序时,上述代码应生成以下消息:

checkNEStatus:  NEVPNConnection: Invalid  
viewDidLoad:    received NEVPNStatusDidChangeNotification  
checkNEStatus:  NEVPNConnection: Connected