Чтобы проверить локальные уведомления, я написал тестовое приложение с одним контроллером представления.
В viewDidLoad
я настраивал пользовательское действие, категорию уведомлений и делегат userNotificationCenter.
В viewDidAppear
я установил содержание уведомления, установил триггер, который срабатывает через 5 секунд, создает запрос на уведомление и добавляет его в центр уведомлений.В локальном уведомлении не отображается кнопка пользовательского действия
Я ожидаю следующее:
переднего плана Режим:
Когда приложение запускается, он должен представить через 5 сек уведомлении на переднем плане. Прежде, должна быть вызвана функция делегата «willPresent notification».
фона Режим:
Если, однако, приложение помещается в фоновом режиме, нажав на кнопку домой, прежде чем триггер срабатывает, уведомление должно быть представлено на главном экране, а функция делегата «уведомление willPresent» не называется ,
После того, как уведомление было представлено, пользователь может нажать кнопку действия.
Это должно принести приложение на передний план и вызвать функцию делегата «didReceive response».
Что происходит:
Кнопка действия в не показано, только название и тело.
Когда я нажимаю тело, функция делегата «didReceive response» запускается с использованием идентификатора действия по умолчанию.
Проблема:
Почему пользовательская кнопка действия не отображается?
Вот мой код:
import UIKit
import UserNotifications
class ViewController: UIViewController, UNUserNotificationCenterDelegate {
let userNotificationCenter = UNUserNotificationCenter.current()
let categotyId = "categoryID"
let actionID = "actionID"
override func viewDidLoad() {
super.viewDidLoad()
userNotificationCenter.requestAuthorization(options: [.alert]) { (granted, error) in
if granted {
let okAction = UNNotificationAction(identifier: self.actionID,
title: "OK",
options: [])
let category = UNNotificationCategory(identifier: self.categotyId,
actions: [okAction],
intentIdentifiers: [],
options: [.customDismissAction])
self.userNotificationCenter.setNotificationCategories([category])
self.userNotificationCenter.delegate = self
} else {
print("local notifications not granted")
}
}
userNotificationCenter.removeAllPendingNotificationRequests()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Title", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "Body", arguments: nil)
content.categoryIdentifier = categotyId
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: (5), repeats: false)
let request = UNNotificationRequest.init(identifier: "requestID",
content: content,
trigger: trigger)
userNotificationCenter.add(request, withCompletionHandler: { (error) in
if let error = error {
print("Could not add notification request. Error: \(error)")
}
})
}
// MARK: - Notification Delegate
// Will be called while app is in the foreground
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// Show alert to the user
print("App in foreground. Show alert.")
completionHandler([.alert])
}
// Should be called after the user tapped the action button
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping() -> Void) {
let request = response.notification.request
let requestID = request.identifier
switch response.actionIdentifier {
case actionID:
print("Custom OK action triggered in background")
case UNNotificationDefaultActionIdentifier:
print("Default action triggered in background")
default:
print("Unknown action triggered in background, action identifier: \(response.actionIdentifier)")
}
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [requestID])
completionHandler()
}
}
Кроме того, на новых iPhone (> iPhone 6s) вы можете принудительно нажать, чтобы вызвать действия (и увидеть дополнительные вложения уведомлений, например изображения). – JanApotheker