在 Android 中,只要系统配置发生变化(如网络状态变化等),操作系统就会发送广播。 这些广播消息可以被我们应用程序中的 broadcastreceiver 接收并相应地改变应用程序的行为,尽管我们的应用程序不处于运行状态。 我如何才能在 iOS 中实现类似的 broadcastreceiver 行为?
最佳答案
您可以使用 NSNotificationCenter
来监控变化。
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "batteryLevelChanged:",
name: NSUserDefaultsDidChangeNotification,
object: nil)
编辑 1:
对于您的情况,您可以按照步骤进行尝试。
- 使用图书馆 Reachability获得关于改变的通知 网络并定义自定义通知功能。
func reachabilityChanged(note: NSNotification) {
let reachability = note.object as! Reachability
if reachability.isReachable() {
if reachability.isReachableViaWiFi() {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
} else {
print("Network not reachable")
}
}
- 在你的通知函数中,创建一个相应的本地 通知
var notification = UILocalNotification()
notification.alertBody = "Notification message!!!" // text that will be displayed in the notification
notification.alertAction = "open" // text that is displayed after "slide to..." on the lock screen - defaults to "slide to view"
notification.fireDate = NSDate() // todo item due date (when notification will be fired)
notification.soundName = UILocalNotificationDefaultSoundName // play default sound
notification.userInfo = ["UUID": UUID, ] // assign a unique identifier to the notification so that we can retrieve it later
notification.category = "CATEGORY"
UIApplication.sharedApplication().scheduleLocalNotification(notification)
关于ios - 如何在未运行状态下在 iOS 上获取有关网络更改的通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36257980/