Push notification with buttons


#1

Всем привет! Передо мной стоит задача - сделать пуш с кнопками - первая открывает экран,вторая скрывает пуш и делает еще одно действие.
Пытаюсь сделать по этому примеру , но приходит обычный пуш без кнопок. Кто такое делал подскажите пожалуйста!!!


#2

А в Notification Payload, group identifier указываете?


#3

Вы об этом?

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()
    }
}

#4

Нет, я про данные, которые отправляете в уведомлении.

И еще, не вижу что бы установили свою группу для уведомления.
Из примера: UNUserNotificationCenter.current().setNotificationCategories([category])


#5

Скорее всего я это упустил. Можете немного подробней объяснить или тыкнуть носом в пример?


#6

6 пункт кода посмотрите.


#7

Вы это имеете в виду?


#8

Именно (_________________)


#9

Я пробовал разные варианты и возможно упустил этот момент, хотя куда то и когда то я его добавлял, только не помню куда и когда


#10

В своем коде вы создали экшены и добавили их в группу, а вот саму группу не добавили к уведомлениям. Плюс посылаемые данные для уведомления должны содержать ID группы, что бы ваше уведомление могло по этому ID понять, что именно для текущего уведомления нужно отобразить экшены.


#11

спасибо за консультацию. буду пробовать))


#12

В вашем примере это все написано

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!


#13

т.е. мне нужно в Pusher добавить еще одно поле, где будет категория “unicorning”?


#14

Именно (________________)


#15

это я упустил из виду. невнимательно читал


#16

А я почему-то начало не читал, сразу к этому моменту прокрутил ))


#17

в этом и разница между опытным разработчиком и начинающим - Вы сразу поняли, где описано основное


#18

Еще нужно учесть, что при работе с Notification Service, у вас очень ограниченное время на выполнение разного рода задач, особенно, если делаете запросы.
Сколько именно времени не знаю, не помню что бы это число где-то упоминалось, но по ощущениям пару секунд.


#19

будет запрос на получение картинки, остальные поля приходят


#20

Если картинка не загрузится за отведенное время, уведомление будет без него, либо стандартным. Этот момент я не помню.