Всем привет! Передо мной стоит задача - сделать пуш с кнопками - первая открывает экран,вторая скрывает пуш и делает еще одно действие.
Пытаюсь сделать по этому примеру , но приходит обычный пуш без кнопок. Кто такое делал подскажите пожалуйста!!!
Push notification with buttons
Вы об этом?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
registerForPushNotifications()
return true
}
func registerForPushNotifications() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
print("granted: \(granted)")
guard granted else { return }
let center = UNUserNotificationCenter.current()
center.delegate = self
let generalCategory = UNNotificationCategory(identifier: "GENERAL", actions: [], intentIdentifiers: [], options: .customDismissAction)
//INVITATION Category
let remindLaterAction = UNNotificationAction(identifier: "remindLater", title: "Remind me later", options: UNNotificationActionOptions(rawValue: 0))
let acceptAction = UNNotificationAction(identifier: "accept", title: "Accept", options: .foreground)
let declineAction = UNNotificationAction(identifier: "decline", title: "Decline", options: .destructive)
let commentAction = UNTextInputNotificationAction(identifier: "comment", title: "Comment", options: .authenticationRequired, textInputButtonTitle: "Send", textInputPlaceholder: "Share your thoughts..")
let invitationCategory = UNNotificationCategory(identifier: "INVITATION", actions: [remindLaterAction, acceptAction, declineAction, commentAction], intentIdentifiers: [], options: UNNotificationCategoryOptions(rawValue: 0))
self.getNotificationSettings()
}
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async(execute: {
UIApplication.shared.registerForRemoteNotifications()
})
}
}
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// iOS10+, called when presenting notification in foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
NSLog("[UserNotificationCenter] applicationState: \(applicationStateString) willPresentNotification: \(userInfo)")
//TODO: Handle foreground notification
completionHandler([.alert, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
{
switch response.notification.request.content.categoryIdentifier
{
case "GENERAL":
break
case "INVITATION":
switch response.actionIdentifier
{
case "remindLater":
print("remindLater")
case "accept":
print("accept")
case "decline":
print("decline")
case "comment":
print("comment")
default:
break
}
default:
break
}
completionHandler()
}
}
Нет, я про данные, которые отправляете в уведомлении.
И еще, не вижу что бы установили свою группу для уведомления.
Из примера: UNUserNotificationCenter.current().setNotificationCategories([category])
Скорее всего я это упустил. Можете немного подробней объяснить или тыкнуть носом в пример?
Я пробовал разные варианты и возможно упустил этот момент, хотя куда то и когда то я его добавлял, только не помню куда и когда
В своем коде вы создали экшены и добавили их в группу, а вот саму группу не добавили к уведомлениям. Плюс посылаемые данные для уведомления должны содержать ID группы, что бы ваше уведомление могло по этому ID понять, что именно для текущего уведомления нужно отобразить экшены.
В вашем примере это все написано
All that is done here is creating the two actions wanted and adding them under a common category(“unicorning”, so original!). That same common category will go in the aps Notification payload we send from Pusher. And that is how the Notification Service would know what notification actions to show!
в этом и разница между опытным разработчиком и начинающим - Вы сразу поняли, где описано основное
Еще нужно учесть, что при работе с Notification Service, у вас очень ограниченное время на выполнение разного рода задач, особенно, если делаете запросы.
Сколько именно времени не знаю, не помню что бы это число где-то упоминалось, но по ощущениям пару секунд.
Если картинка не загрузится за отведенное время, уведомление будет без него, либо стандартным. Этот момент я не помню.