应用在后台运行时不显示 UNUser通知



我正在尝试在指定的延迟后在后台触发本地通知,但由于某种原因,从我的应用程序计划时没有显示它。我创建了一个基本测试应用程序来测试相同代码在指定的延迟后按预期显示计划通知的行为,因此我已确认我的代码是正确的。但是,相同的代码在我的应用程序中不会产生相同的结果。我有正确的权限等,但通知没有显示。它将显示在前台,只是当应用程序在后台时不会显示。我还在计划后检查了待处理的通知,以查看它是否在队列中并且确实存在。我已经在代码中搜索了对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)
})
}

以下是我AppDelegate中的权限注册和UNUserNotificationCenterDelegate实现:

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

我还应该补充一点,在测试中,它有几次是随机触发的。有一次我在添加请求完成块中设置断点时......

尝试向内容添加正文:

content.body = "Some content"

我不确定另一个示例应用程序是如何工作的,并且您的主应用程序没有使用相同的代码。但我也不明白前台通知如何在没有内容的情况下为您显示

最新更新