William  Sterling William Sterling - 11 months ago 238
iOS Question

NEVPNManager check is connected after restart the app?

I coding a VPN tool, using the

framework. I can connect IPSec through
, and can grab the notification when VPN connect status changed. But when I kill the app, and reopen it, the
always Zero, than means can't display the correct connect state. How to solve it?

Answer Source

Try this:

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

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

The above code should generate the following messages when running the app with VPN already connected:

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