我正在编写一个使用NetworkExtension
框架的VPN工具。我可以通过NEVPNManager.sharedManager
连接IPSec,并且可以在VPN连接状态改变时获取通知。但是当我关闭应用程序并重新打开它时,NEVPNManager.Connect.Status
始终为零,这意味着无法显示正确的连接状态。如何解决这个问题?
我正在编写一个使用NetworkExtension
框架的VPN工具。我可以通过NEVPNManager.sharedManager
连接IPSec,并且可以在VPN连接状态改变时获取通知。但是当我关闭应用程序并重新打开它时,NEVPNManager.Connect.Status
始终为零,这意味着无法显示正确的连接状态。如何解决这个问题?
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)
}
试试这个:
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")
}
}
checkNEStatus: NEVPNConnection: Invalid
viewDidLoad: received NEVPNStatusDidChangeNotification
checkNEStatus: NEVPNConnection: Connected
var notificationObserver:NSObjectProtocol?
- hungri-yeti