8

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

4

2 回答 2

8

威廉斯特林的评论确实有道理,它对我有用,

在为 VPN 管理器对象添加负载首选项的观察者之前,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)

     }
于 2017-12-07T07:11:50.177 回答
5

试试这个:

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
于 2016-08-21T04:42:07.100 回答