【发布时间】:2019-03-21 19:04:19
【问题描述】:
我正在尝试在指定的延迟后在后台触发本地通知,但由于某种原因,在我的应用程序安排时它没有显示。我创建了一个简单的测试应用程序来测试相同代码在指定延迟后按预期显示预定通知的行为,因此我确认我的代码是正确的。但是,相同的代码在我的应用程序中不会产生相同的结果。我有正确的权限等,但通知没有显示。它将显示在前台,而不是当应用程序在后台时。我还在安排后检查了待处理的通知,以查看它是否在队列中并且确实存在。我在代码中搜索了对 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
我还应该补充一点,在测试中,它已经有几次随机触发了。有一次我在添加请求完成块中设置断点...
【问题讨论】:
-
您在控制台中得到了什么跟踪?
-
@barbarity 查看更新
-
尝试删除所有待处理的通知,然后重试或重新启动您的设备。根据代码,它应该是完美的,但看起来您的设备无法正常工作。
-
@barbarity 我都试过了,但没有任何乐趣。我不相信这是设备,因为测试应用程序运行良好......困惑:(
-
不清楚“有效”和“无效”是什么意思。您期望什么以及实际会发生什么?
标签: ios swift unusernotificationcenter