如何在 iOS 中终止应用程序时禁用 vpn 连接?

How to disable vpn connection when app is terminated in iOS?

我正在通过 PacketTunnel 实施个人 VPN。通过 NETunnelProviderManager 的 startVPNTunnel 方法,我检查了 VPN 连接是否 运行 好。

但是,我有一个问题。我在 applicationWillTerminate 中添加了 vpn 连接的退出代码,以在应用程序终止时禁用 vpn 连接,如下面的代码所示。但是没用。

如果测试这段代码,loadAllFromPreferences 是 运行 但 loadAllFromPreferences 的回调函数没有被调用。此代码 运行 可以在除 applicationWillTerminate 之外的任何地方使用。为什么它不起作用?有没有办法在应用程序终止时禁用 vpn?

func applicationWillTerminate(_ application: UIApplication) {
        NETunnelProviderManager.loadAllFromPreferences { (managers, error) in
            var manager:NETunnelProviderManager?=nil;
            for m in managers! {
                if m != nil {
                    if m.localizedDescription == "profile" {
                        manager = m;
                        break
                    }
                }
            }
            manager?.connection.stopVPNTunnel()
        }
    }

根据 applicationWillTerminate(application:) 的 Apple documentation

Your implementation of this method has approximately five seconds to perform any tasks and return. If the method does not return before time expires, the system may kill the process altogether.

如果 applicationWillTerminate 被调用但闭包未确保它不会超过“大约”(原文如此)5 秒。

我没有使用过您正在使用的库,但从一般的角度来看,可能有比遍历所有可用管理器更好的策略。就像在启动连接时将 reference/identifier 存储到给定的管理器并使用该 reference/identifier 来终止它。