iOS VPN auto disconnected after sometime

1.3k Views Asked by At

I'm working on a VPN application, VPN working fine but after 15-20 minutes, its automatically disconnected. Here is configuration I'm using

        let vpnProtocol = NEVPNProtocolIKEv2()
        vpnProtocol.username = CredentialsManager.shared.accessToken
        vpnProtocol.localIdentifier = CredentialsManager.shared.accessToken

        print("VPN Connecting to \(self.region.name ?? "Error! Must be a valid region name!")")

        if let region = self.region {
          f
            vpnProtocol.serverAddress = region.serverAddress
            vpnProtocol.remoteIdentifier = region.serverAddress
        }

        let encodedIdentifier = "Secret Password".data(using: .utf8)!
        let item = [kSecClass: kSecClassGenericPassword,
                    kSecAttrGeneric: encodedIdentifier,
                    kSecAttrAccount: encodedIdentifier,
                    kSecMatchLimit: kSecMatchLimitOne,
                    kSecReturnPersistentRef: kCFBooleanTrue as Any,
                    kSecAttrService: "XYZ"] as [CFString : Any]

        var passwordReference: CFTypeRef?
        SecItemCopyMatching(item as CFDictionary, &passwordReference)

        vpnProtocol.passwordReference = passwordReference as? Data
        vpnProtocol.authenticationMethod = .none
        vpnProtocol.useExtendedAuthentication = true

        vpnProtocol.ikeSecurityAssociationParameters.encryptionAlgorithm =
            .algorithmAES256GCM
        vpnProtocol.ikeSecurityAssociationParameters.integrityAlgorithm = .SHA384
        vpnProtocol.ikeSecurityAssociationParameters.diffieHellmanGroup = .group14

        vpnProtocol.childSecurityAssociationParameters.encryptionAlgorithm = .algorithmAES256GCM
        vpnProtocol.childSecurityAssociationParameters.integrityAlgorithm = .SHA384
        vpnProtocol.childSecurityAssociationParameters.diffieHellmanGroup = .group14

        vpnProtocol.disconnectOnSleep = false

        self.vpnManager.protocolConfiguration = vpnProtocol
        let connectRule = NEOnDemandRuleConnect()
        connectRule.interfaceTypeMatch = .any

        self.vpnManager.onDemandRules = [connectRule]
        self.vpnManager.isOnDemandEnabled = self.connectOnDemand
        self.vpnManager.localizedDescription = "XYZ VPN"
        self.vpnManager.isEnabled = true

Please help me out, how to identify problem that causing auto disconnect.

2

There are 2 best solutions below

5
On

change your VPN protocol with this: NEVPNProtocolIPSec maybe it will help you.

2
On

You have configured "connect on demand", so it will connect back automatically when you will access resource next time. That is how VPN on iOS works, it will always close connection on idle.