From ac29886f7b37bf5028740565f8f9c3840601acdf Mon Sep 17 00:00:00 2001 From: Roopesh Chander Date: Sun, 28 Oct 2018 18:09:38 +0530 Subject: [PATCH] VPN: A tunnel may be already active on app startup --- WireGuard/WireGuard/VPN/TunnelsManager.swift | 30 ++++++++++++++------ 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/WireGuard/WireGuard/VPN/TunnelsManager.swift b/WireGuard/WireGuard/VPN/TunnelsManager.swift index 37b4b90..d320e1d 100644 --- a/WireGuard/WireGuard/VPN/TunnelsManager.swift +++ b/WireGuard/WireGuard/VPN/TunnelsManager.swift @@ -34,10 +34,18 @@ class TunnelsManager { init(tunnelProviders: [NETunnelProviderManager]) { var tunnels = tunnelProviders.map { TunnelContainer(tunnel: $0, index: 0) } tunnels.sort { $0.name < $1.name } + var currentTunnel: TunnelContainer? = nil for i in 0 ..< tunnels.count { - tunnels[i].index = i + let tunnel = tunnels[i] + tunnel.index = i + if (tunnel.status != .inactive) { + currentTunnel = tunnel + } } self.tunnels = tunnels + if let currentTunnel = currentTunnel { + setCurrentTunnel(tunnel: currentTunnel) + } } static func create(completionHandler: @escaping (TunnelsManager?) -> Void) { @@ -169,14 +177,7 @@ class TunnelsManager { return } tunnel.startActivation(completionHandler: completionHandler) - currentTunnel = tunnel - currentTunnelStatusObservationToken = tunnel.observe(\.status) { [weak self] (tunnel, change) in - guard let s = self else { return } - if (tunnel.status == .inactive) { - s.currentTunnel = nil - s.currentTunnelStatusObservationToken = nil - } - } + setCurrentTunnel(tunnel: tunnel) } func startDeactivation(of tunnel: TunnelContainer, completionHandler: @escaping (Error?) -> Void) { @@ -188,6 +189,17 @@ class TunnelsManager { tunnel.startDeactivation() } + + private func setCurrentTunnel(tunnel: TunnelContainer) { + currentTunnel = tunnel + currentTunnelStatusObservationToken = tunnel.observe(\.status) { [weak self] (tunnel, change) in + guard let s = self else { return } + if (tunnel.status == .inactive) { + s.currentTunnel = nil + s.currentTunnelStatusObservationToken = nil + } + } + } } extension NETunnelProviderProtocol {