3

我正在尝试创建一个 VPN 应用程序,当 VPN 在设置应用程序中手动关闭时通知用户。更一般地说,我希望能够在网络设置更改时做出反应。我在 StackOverflow 上看到了很多关于可达性、网络等的评论,但我不知道我是否可以在后台检查这些东西。有没有办法通过使用“获取”或“远程通知”来做到这一点。我的手机上有一个应用程序,如果我关闭 VPN,它会给我一个通知,所以我知道有办法做到这一点,但我不知道怎么做。

4

2 回答 2

1

根据这个 Apple Developer Discussion

答案可能是否定的。Apple 员工可能会回答此 Apple 开发人员讨论。

没有在网络更改时在后台运行代码的机制。大多数需要做这类事情的人都使用 VPN On Demand 架构。VPN On Demand 有一个 API,但该 API 直接映射到配置文件属性,并且配置文件不被视为 API(这意味着它们由 Apple 支持部门提供支持,而不是由开发人员技术支持部门提供支持)。

于 2021-05-28T12:37:23.277 回答
0

这将每 3 秒监控一次您的互联网状态:

import Cocoa
import Darwin
import Network

//DispatchQueue.global(qos: .userInitiated).async {
let monitor = NWPathMonitor()
let queue = DispatchQueue(label: "Monitor")
monitor.start(queue: queue)
var count = 10


while count >= 0 {
    
monitor.pathUpdateHandler = { path in
    
    if path.status == .satisfied {
        print("There is internet")
        
        if path.usesInterfaceType(.wifi) { print("wifi") }
        else if path.usesInterfaceType(.cellular) { print("wifi") }
        else if path.usesInterfaceType(.wiredEthernet) { print("wiredEthernet") }
        else if path.usesInterfaceType(.loopback) { print("loopback") }
        else if path.usesInterfaceType(.other) { print("other") }

        
    } else {
        print("No internet")
    }
    
}
   sleep(3)
   count = count - 1
}

monitor.cancel()
//}

此代码每三秒返回一次互联网状态和连接类型。如果您希望它永远运行,请将其更改while count >= 0while truewithDispatchQueue.global(qos: .userInitiated).async {或者DispatchQueue.global(qos: .background).async {您可以将任务移至后台。
要继续在后台运行代码(当应用程序不存在时),请遵循https://www.hackingwithswift.com/example-code/system/how-to-run-code-when-your-app-is-terminated

注意:在使用可达性框架时,Appstore 有时会拒绝您的应用。

于 2021-05-29T13:26:43.700 回答