ios - 如何在未运行状态下在 iOS 上获取有关网络更改的通知

标签 ios swift

在 Android 中,只要系统配置发生变化(如网络状态变化等),操作系统就会发送广播。 这些广播消息可以被我们应用程序中的 broadcastreceiver 接收并相应地改变应用程序的行为,尽管我们的应用程序不处于运行状态。 我如何才能在 iOS 中实现类似的 broadcastreceiver 行为?

最佳答案

您可以使用 NSNotificationCenter 来监控变化。

NSNotificationCenter.defaultCenter().addObserver(
    self,
    selector: "batteryLevelChanged:",
    name: NSUserDefaultsDidChangeNotification,
    object: nil)

这是 API 引用: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/

编辑 1:

对于您的情况,您可以按照步骤进行尝试。

  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")
  }
}
  1. 在你的通知函数中,创建一个相应的本地 通知

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/

相关文章:

ios - NSXMLParser 不工作

iphone - UItableview 和搜索栏以及 xib 中的自定义单元格

ios - 警报 View 没有确定/关闭按钮?

ios - 自定义几何网格——如何进行三角剖分以使其看起来平滑

ios - 无法将类型 '__NSSingleObjectArrayI' 的值转换为 'NSDictionary'

ios - 将 UIView 转换到 SKView 时线程 1 信号 SIGABRT 崩溃

javascript - iOS 7 - 修复了虚拟键盘上的页脚工具栏中断问题

ios - 与自定义类而不是 SLComposeServiceViewController 共享扩展

ios - 由于 Arm64 和 Armv7,构建失败?

ios - 更新后无法打开 Realm Studio - Realm 文件当前在另一个进程中打开 - Mac 和 Realm Swift