gpt4 book ai didi

整个应用程序中的 IOS 可达性以及仅在 View 加载时的可达性

转载 作者:行者123 更新时间:2023-11-30 13:07:17 24 4
gpt4 key购买 nike

我已将以下代码添加到 View Controller 的 viewDidLoad 中:

let reachability: Reachability
do {
reachability = try Reachability.reachabilityForInternetConnection()
} catch {
print("Unable to create Reachability")
return
}

reachability.whenReachable = { reachability in
// this is called on a background thread, but UI updates must
// be on the main thread, like this:
dispatch_async(dispatch_get_main_queue()) {
if reachability.isReachableViaWiFi() {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
}
}
reachability.whenUnreachable = { reachability in
// this is called on a background thread, but UI updates must
// be on the main thread, like this:
dispatch_async(dispatch_get_main_queue()) {
print("Not reachable")
}
}

do {
try reachability.startNotifier()

} catch {
print("Unable to start notifier")
}

它通知我 View 何时加载,但不通知我加载后状态发生变化。我想知道如何扩展它,以便我可以在应用程序中的任何位置收到通知,而不仅仅是在 View 加载时收到通知,因为互联网可能会在 View 加载后返回。

谢谢

最佳答案

您应该将可达性变量声明为实例变量,而不仅仅是函数内的局部变量。您可以进一步使用通知来使信息在您的应用程序中可用。只需确保包含可达性变量的实例在应用程序的生命周期中存在即可。

关于整个应用程序中的 IOS 可达性以及仅在 View 加载时的可达性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39185075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com