1

I have implemented one successful vpn connection. But When i close and Open app while the VPN is connected, then i can't disconnect the VPN.

public func connectVPN() {
    //For no known reason the process of saving/loading the VPN configurations fails.On the 2nd time it works
    Log.d(message:  "connectVPN")
    NSLog("ConnectVPN")
    self.vpnManager.loadFromPreferences(completionHandler: self.vpnLoadHandler)
    NotificationCenter.default.addObserver(forName: NSNotification.Name.NEVPNStatusDidChange, object: nil , queue: nil) {
        notification in
        let nevpnconn = notification.object as! NEVPNConnection
        let status = nevpnconn.status
        self.vpnDelegate?.checkNES(status: status)
    }
}

public func disconnectVPN() ->Void {
    Log.d(message:  "Disconnect VPN Called")
    Log.d(message: "Log Disconnect VPN Called")
    
    print("vpnManager:disconnectVPN \(self.vpnManager.connection) ") // object available
    
    self.vpnManager.connection.stopVPNTunnel()
}

I could not find out why it is not disconnecting.

Wasi Sadman
  • 1,382
  • 1
  • 15
  • 27
  • 2
    It's a mess, but after creating new `NETunnelProviderManager` and saving it to preferences with `saveToPreferences()`, you always have to call `tunnelProvider.loadFromPreferences()`. So maybe that's why. – pronebird Nov 25 '21 at 09:54
  • Can you please suggest me any resource that follows your thought? It would be very helpful. i have been stuck here for 3 days now. – Wasi Sadman Nov 25 '21 at 09:58

1 Answers1

3

Call stopVPNTunnel() inside loadFromPreferences closure.

NEVPNManager.shared().loadFromPreferences { error in
  assert(error == nil, "Failed to load preferences: \(error!.localizedDescription)")
  NEVPNManager.shared().connection.stopVPNTunnel()
}
sz ashik
  • 881
  • 7
  • 20