A while ago, I published a post about configuring and managing VPN connections programmatically in iOS 8. By default, established VPN connection will be disconnected if user iOS device goes to sleep to save battery life. To avoid this, Apple introduced a feature called on-demand; so, iOS will get connected to VPN whenever it needs to connect to the internet.
Well, it can be implemented programmatically too using the NetworkExtension framework and that’s exactly what this post is all about. In this post, I am going to create an on-demand VPN connection using NetworkExtension; therefore, VPN connection will be established whenever an app opens a network connection.
Note: I am not going to describe how to create a VPN connection in this post. If you’re not familiar with creating a VPN connection programmatically, please take a checkout my post.
Turn on On-Demand
The first thing you need to do is to tell the NetworkExtension framework that you want to create an on-demand connection. To do so, set the
onDemandEnabled property to
[[NEVPNManager sharedManager] setOnDemandEnabled:YES];
turning on-demand on is not enough. You will also need to tell the OS when exactly you want on-demand to be enabled. To do so, you will need to assign some rules to your configuration. These rules called “On-demand rules”:
What are On-demand rules?
On-demand rules are set of attributes which must be set to tell the OS when VPN connection should be established on-demand.
onDemandRules property accepts an array of rules. Consequently, you can set multiple rules for a VPN configuration.
For example, you can set a rule and tell the OS to establish the VPN connection whenever user wants to open Apple.com; otherwise, the VPN connection won’t be established.
One thing you may want to do it to activate the VPN connection whenever an app open a network connection; so, all iOS network traffic will be transferred through your VPN server. To achieve this,
NEOnDemandRuleConnect class must be used.
In Network Extension framework, Apple has provided some useful on-demand rule templates you can make use of. Although you can create your own rule, it’s possible to use templates as well.
NEOnDemandRuleConnect class is one of those templates. It will tell the OS to establish VPN connection whenever iOS needs to connect to the internet; as a result, users will always connect to your VPN servers whenever they want to access the internet. As far as I know, this is what most VPN providers and users want:
[[NEVPNManager sharedManager] setOnDemandEnabled:YES]; NSMutableArray *rules = [[NSMutableArray alloc] init]; NEOnDemandRuleConnect *connectRule = [NEOnDemandRuleConnect new]; [rules addObject:connectRule]; [[NEVPNManager sharedManager] setOnDemandRules:array];
Once you changed the configuration you have to save it using
Hope it helps 🙂