设备重启后的本地通知

Local Notifications After Device Restart

我启动我的应用程序并安排我的本地通知。这是我使用的代码的简化版本:

let content = UNMutableNotificationContent()
content.body = "Wild IBEACON appeared!"
let region = CLBeaconRegion(proximityUUID: uuid, identifier: "iBeacon region")
let trigger = UNLocationNotificationTrigger(region: region, repeats: true)
let request = UNNotificationRequest(identifier: "iBeacon notification", content: content, trigger: trigger)
notificationCenter.add(request)

它们在我的应用程序处于后台时触发。到目前为止,还不错。

然后我重启设备。我不会强制退出应用程序。
现在通知不再触发。我需要重新打开应用程序。

有没有办法让我的日程安排在重启后继续有效?

UNLocationNotificationTrigger 是在 iOS10 中添加的新助手 classes,可以更轻松地触发基于信标或地理围栏检测的通知。 根据文档,它被设计为仅在应用程序正在使用时使用:

Apps must request access to location services and must have when-in-use permissions to use this class. To request permission to use location services, call the requestWhenInUseAuthorization() method of CLLocationManager before scheduling any location-based triggers.

https://developer.apple.com/reference/usernotifications/unlocationnotificationtrigger

基于以上权限,应用只会在使用时触发。 文档没有明确说明它不会在后台运行,因此您可以尝试请求 always 位置权限requestAlwaysAuthorization() 而不是 requestWhenInUseAuthorization()(如果这样做,请确保将正确的密钥放入 plist),看看是否有帮助。

另一种方法是不使用此助手 class 而是手动启动 CoreLocation 和信标监控,然后在获得区域进入回调时手动创建自己的 UILocalNotification :

func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
  if let region = region as? CLBeaconRegion {
    let notificationMessage = "Wild IBEACON appeared!"
    let notification = UILocalNotification()
    notification.alertBody = notificationMessage
    notification.alertAction = "OK"
    UIApplication.shared.presentLocalNotificationNow(notification)
  }
}

已知上述方法适用于应用重启。