Search code examples
iosvpnnevpnmanager

iOS VPN configuration keeps disconnecting when on battery


I've set up a IKEv2 VPN configuration in my app, using NEVPNManager. The intention is for the connection to remain active until the user toggles it off, or is terminated by the VPN server. For that purpose, I've set the following configuration:

let protocol = NEVPNProtocolIKEv2()
...
protocol.disconnectOnSleep = false

However, if the iPhone is running on battery, the VPN is still disconnected after a while when the device is left idle. This doesn't seem to be occurring if I leave it plugged in to the charger.

I've already looked into setting up OnDemandRules, which re-establishes the connection when the device wakes up, but that causes another problem, that the device keeps trying to reconnect even if the VPN server closed it. Is there a better way to implement the rule I'm looking for (stay connected until user or server closes it)?


Solution

  • The issue was not caused by iOS going into sleep mode, that was purely coincidental. The reason for the disconnects was because the IKEv2 configuration accidentally had the localIdentifier set to a fixed value. This meant that if a device tried to connect to the VPN server, any existing connections would be dropped, because as far as the server is concerned, they're all from the same source, as they have the same local identifier.

    So if you're running into this problem, make sure each device gets something unique as the local identifier. Using the Apple device ID is a good option.