我正在尝试在指定的延迟后使本地通知在后台触发,但是由于某些原因,从我的应用进行调度时未显示该通知。我创建了一个简单的测试应用程序,以测试行为,其中相同的代码按预期在指定的延迟后显示计划的通知,因此我确认我的代码是正确的。但是,相同的代码在我的应用程序中不会产生相同的结果。我具有正确的权限等。但通知未显示。它会显示在前景中,而不会在后台显示。我还安排了计划后检查了待处理的通知,以查看它是否在队列中并且确实存在。我已经在代码中搜索了对UNUserNotificationCenter.current()
的任何引用,并添加了断点和注释代码以确保没有其他交互。
以下是触发通知并验证是否已将其添加到队列中的代码:
let content = UNMutableNotificationContent()
content.title = "Tap to trigger test"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
print("error", error)
UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: { (requests) in
print("requests", requests.count)
})
}
以下是我的UNUserNotificationCenterDelegate
中的权限注册和AppDelegate
实现:
public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(.alert)
}
public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print(response)
}
public func registerForPushNotifications() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] granted, error in
print("Permission granted: \(granted)")
guard granted else { return }
self?.getNotificationSettings()
}
}
public func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { settings in
print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
控制台输出:
Permission granted: true
Notification settings: <UNNotificationSettings: 0x280565260; authorizationStatus: Authorized, notificationCenterSetting: Enabled, soundSetting: Enabled, badgeSetting: Enabled, lockScreenSetting: Enabled, carPlaySetting: NotSupported, criticalAlertSetting: NotSupported, alertSetting: Enabled, alertStyle: Banner, providesAppNotificationSettings: No>
error nil
requests 1
我还应该补充一点,在测试中,它已经随机触发了几次。一次,当我在添加请求完成块中设置断点时...
答案 0 :(得分:0)
尝试在内容中添加正文:
content.body = "Some content"
我不确定其他示例应用程序如何工作,并且您的主应用程序没有相同的代码。但是我也不明白前台通知如何在没有content.body的情况下显示给您。