我启动我的应用程序并安排我的本地通知。这是我正在使用的代码的简化版本:
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 中添加的新帮助程序类,可以更轻松地根据信标或地理围栏检测触发通知。 根据文档,它被设计为仅在应用程序使用时使用:
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
基于上述权限,该应用程序仅在使用时才会触发。 文档没有明确说明它无法在后台运行,因此您可以尝试使用 requestAlwaysAuthorization()
请求始终位置权限而不是 requestWhenInUseAuthorization()
(如果执行此操作,请确保将正确的 key 放入 plist 中),看看这是否有帮助。
另一种方法是不使用此帮助程序类,而是手动启动 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)
}
}
众所周知,上述方法可以在应用重新启动时发挥作用。
关于ios - 设备重启后的本地通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41695740/