Я пытаюсь получить локальное уведомление для запуска в фоновом режиме после указанной задержки, но по какой-то причине оно не отображается при планировании из моего приложения. Я создал тестовое приложение «голые кости», чтобы проверить поведение, в котором тот же код отображает запланированное уведомление после указанной задержки, как и ожидалось, поэтому я подтвердил, что мой код правильный. Однако тот же код не дает того же результата в моем приложении. У меня есть правильные разрешения и т.д., но уведомление не отображается. Он будет отображаться на переднем плане, но не в фоновом режиме. Я также проверил ожидающие уведомления после планирования, чтобы увидеть, находится ли он в очереди и действительно ли он там. Я искал код для любой ссылки на 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
Я должен также добавить, что при тестировании несколько раз он срабатывал случайно. Однажды, когда я установил точку останова в блоке завершения запроса на добавление ...