Connect to VPN with Swift 3

I am trying to connect to VPN on an iOS app. What I already know is the VPN type (L2TP over IPSec), account name, password and shared secret. The connection works through the Mac network settings. Although it seems a bit tricky when you need to use this information in your code.

First, I imported the required library.

import NetworkExtension

      

Then I try to load the settings and in case of error I use my own and save it. Looks like that:

NEVPNManager.shared().loadFromPreferences { error in
        // config
        NEVPNManager.shared().saveToPreferences { error in
            if (error == nil) {
                do {
                    try NEVPNManager.shared().connection.startVPNTunnel()
                } catch {
                    print("Couldn't connect")
                }
            } else {
                print("NEVPNManager.saveToPreferencesWithCompletionHandler failed: \(error!.localizedDescription)")
            }
        }
    }

      

If you see "// config" my data should be transferred. I'm not 100% sure if I'm doing it right.

There the constant let p = NEVPNProtocolIPSec()

is where I put my data. It looks like p.username = "smth"

.

Question: which fields p

must be filled in? Where can I put my shared secret?

--- UPDATE ---

I always get the error:

NEVPNManager.saveToPreferencesWithCompletionHandler failed: The operation could not be completed. (NEVPNErrorDomain error 4.)

I can't find anything specific about this.

Do the .sharedSecretReference and .passwordReference fields require data during configuration? an object. I get it using keychain.get("passref")?.data(using: .utf8, allowLossyConversion: true)

, preceded by

let keychain: KeychainSwift! = KeychainSwift()

keychain.set("<my_password>", forKey: "passref")

      

(the KeychainSwift class comes from here )

Where am I making a mistake?

+3


source to share





All Articles