Connecting to VPN with Swift 3

1.7k Views Asked by At

I'm trying to connect to a VPN in an iOS app. What I already know is the VPN type (L2TP over IPSec), account name, password and shared secret. The connection works through Mac's Network settings. Although, it seems a little more complicated, when you have to use this info in code.

First, I have imported the necessary library.

import NetworkExtension

Then, I'm trying to load preferences and in case of error, I'm using my own and save them. Looks like this:

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)")
            }
        }
    }

Where you can see the "// config", my data should be passed. I'm not 100% sure, if I'm doing it right.

There's a constant let p = NEVPNProtocolIPSec() where I'm placing my data. It's like p.username = "smth".

The question is: which fields of p should be filled? Where do I put the shared secret?

--- UPDATE ---

I'm always getting the error:

NEVPNManager.saveToPreferencesWithCompletionHandler failed: The operation couldn’t be completed. (NEVPNErrorDomain error 4.)

I can't find anything specific about that.

During the config, fields .sharedSecretReference and .passwordReference require the Data? object. I'm getting it by using keychain.get("passref")?.data(using: .utf8, allowLossyConversion: true) preceded by

let keychain: KeychainSwift! = KeychainSwift()

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

(class KeychainSwift comes from here)

Where am I making a mistake?

0

There are 0 best solutions below