How to disconnect VPN after app is terminated ios swift

895 views Asked by At

Basically i am working on VPN app and i want to put restriction for free user in my app. Free user can connect to VPN with 1GB of limit like TunnelBear app.

I have use this code and VPN connect/disconnect working fine. Create Personal VPN connection using NEVPNManager

Do i need to add some rule in NEOnDemandRule to achieve this?

If i connect to VPN and close the app VPN still be connected in this case how can i restrict free user limit to 1GB while app terminated.

Any suggestion will be very helpful.

3

There are 3 answers

0
Amro Jaber On

I used these simple codes and it works perfect

import NetworkExtension
            
class yourViewController: UIViewController {
                  
    let manager: NEVPNManager = { NEVPNManager.shared() }()
                
    override func viewDidLoad() {
        super.viewDidLoad()

        //just add this Notification to observe if app terminated
        NotificationCenter.default.addObserver(forName: UIApplication.willTerminateNotification, object: nil, queue: nil) { _ in
            self.manager.connection.stopVPNTunnel()
            print("terminated")
        }
    }
}
3
Eric33187 On

Your app will not continuously run in the background unless it implements a feature that requires it (e.g. playing audio, receiving location updates, or processing scheduled tasks). See this helpful article in the Apple Docs for more info.

The best way to handle your case is to suspend the timer when the app is sent to the background, and then restart it once it re-enters the foreground.

0
Witterquick On

You'll need to implement the VPN yourself, i.e. with a Packet Tunnel Provider. Then you'll be able to count 1GB of traffic and to disconnect the VPN.