重启应用后NEVPNManager检查是否连接?

NEVPNManager check is connected after restart the app?

我编写了一个 VPN 工具,使用 NetworkExtension 框架。我可以通过 NEVPNManager.sharedManager 连接 IPSec,并且可以在 VPN 连接状态改变时抓取通知。但是当我终止应用程序并重新打开它时,NEVPNManager.Connect.Status 始终为零,这意味着无法显示正确的连接状态。如何解决?

试试这个:

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

William Sterling 评论确实有道理,而且对我有用,

在为 NEVPNStatusDidChange 添加观察者之前,为如下所示的 VPN 管理器对象加载首选项,

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)

     }