在后台检测网络更改(iOS)



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

根据这次苹果开发者讨论:

答案可能是。苹果开发者的讨论可能会得到苹果员工的回答。

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

这将每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()
//}

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

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

最新更新