Restart Packet Tunnel Provider when network is changed

So, I've implemented a Packet Tunnel Provider in order to create a custom VPN protocol, and it's working fine. However, If i change network's (i.e. switch from WiFi to LTE), the connection is lost. I thought "Well, I'll just wait till the connection drops and restart the provider", but in order for iOS to completely change adapters, it requires that all VPN providers are terminated.


So, I'm curious how I would restart the provider after the network has been changed. I've been unable to handle it in the primary application target since it would need to automatically restart even if the app is not open in the background, that way I don't have to re-connect to the VPN every time I leave the house and leave WiFi.


Any suggestions?

Replies

I think you have two choices here:

  • If you’ve decided that the VPN connection is completely toast, you can call

    -[NEPacketTunnelProvider cancelTunnelWithError:]
    to completely shut it down.

    WARNING Only do this if the VPN connection is fully up. If it’s coming up, you should call the completion handler that was passed to

    -startTunnelWithOptions:completionHandler:
    . If it’s going down, you should call the completion handler that was passed to
    -stopTunnelWithReason:completionHandler:
    . See
    PacketTunnelProvider.tunnelDidClose(targetTunnel:)
    in the SimpleTunnel sample code for an example of this.
  • If the VPN connection might be recoverable (for example, by reconnecting over the new link) you can set NETunnelProvider’s

    reasserting
    property and start that recovery process. When it’s done, clear
    reasserting
    .

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

The issue with bringing the tunnel down is that the primary app has to be open in order to start a new PacketTunnelProvider. This needs to operate regardless of if the front end app is open or not. That way, if someone leaves their WiFi network the application will seemlessly maintain the VPN connection while the phone hops between the networks.


Do you have an example of using the reasserting property? I'd love to see how it's used since I've not been able to get it working since i started working on this.


Thanks

The issue with bringing the tunnel down is that the primary app has to be open in order to start a new PacketTunnelProvider.

Why is that? That’s not generally a requirement for Network Extension packet tunnel providers. For example, the user can start the VPN from Settings > VPN.

Do you have an example of using the reasserting property?

No, sorry.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"