Search code examples
swiftxcodevpnnevpnmanager

iOS VPN on Demand rules


I want to create a onDemandRule for VPN connnection in ios

Requirement is as follows.

If Both cellular and wifi is available and wifi ssid = "ABC" than only VPN will run otherwise it should stop.

I have tried following OnDemandRule

             let onDemandRule = NEOnDemandRuleConnect()
            onDemandRule.interfaceTypeMatch = .wiFi
            onDemandRule.ssidMatch = ["ABC"]

            let onDemandRule1 = NEOnDemandRuleConnect()
            onDemandRule1.interfaceTypeMatch = .cellular                
            self.vpnManager.isOnDemandEnabled = true

            let onDemandRule2 = NEOnDemandRuleDisconnect()
            onDemandRule2.interfaceTypeMatch = .any

            self.vpnManager.onDemandRules = [onDemandRule, onDemandRule1, onDemandRule2]

It works as soon as i connect to a wifi named ABC

But it doesn't disconnect if i switch off cellular data. Can someone please let me know what i am doing wrong here.


Solution

  • You should read the rules like a set of firewall rules, NEVPNManager goes through the list of rules and the first rule that applies is followed. In your example when you would switch off cellular data it will evaluate rule 1: wifi + SSID "ABC". If that rules satisfies i.e. you are connected to WiFi SSID "ABC", the vpn will be connected. If not, NEVPNManager will go through the next rule.

    If you switch off cellular, the first rule still applies. (You can still have a WiFi connection). NEVPNManager can't differentiate between cellular on/off. It can only differentiate between which interface is used: cellular, WiFi or any.