@Wolfak

Почему в IOS приходит один пуш но уведомления отображается два?

Добрый день.

Я отправляю с backend части приложения пуш уведомление в iOS и Android приложение
Просисываю в запросе пуша следующее:
Array ( [registration_ids] => Array ( [0] => test_token ) [notification] => Array ( [title] => Заголовок уведомления [body] => Текст уведомления [sound] => 1 [content_available] => 1 [priority] => high [badge] => 4 [smallIcon] => small_logo [click_action] => .NoticeFullController ) [data] => Array ( [short_text] => Короткий текст уведомления [selectNotice] => 123 [selectStatus] => 4 ) [apns] => Array ( [headers] => Array ( [apns-priority] => 5 ) [payload] => Array ( [aps] => Array ( [category] => notice_push ) ) ) )

С Android приложением проблем нет, но в iOS происходит следующее:
1. Если приложение в фоне или закрыто уведомление отображается одно, но при клике на него открывается главная страница приложения, а нужно чтобы открывалась страница с полным видом уведомления с ID из поля 'selectNotice' в запросе если оно больше 0, иначе главная страница.
2. Если приложение открыто, то при первом запуске есть только звуковой сигнал приложения и ничего больше. А должно выводиться уведомление, а не только его звук.
3. При следующей отправке пуша отображается два уведомления, один из которых из background режима, второе создается моим кодом, а нужно чтобы было всего лишь одно. И при клике на него открывается главная страница приложения, а нужно чтобы открывалась страница с полным видом уведомления с ID из поля 'selectNotice' в запросе если оно больше 0, иначе главная страница.

Помогите разобраться с пушами в iOS. Заранее огромное спасибо. Мой код AppDelegate:
import UserNotifications
import Firebase
import FirebaseMessaging

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        // Use Firebase library to configure APIs
        FirebaseApp.configure()
        
        // Уведомления в фоне
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in})
        
        // Override point for customization after application launch.
        return true
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    {
        completionHandler([.alert, .badge, .sound])
    }
    func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    {
        //Handle the notification
        completionHandler(
            [UNNotificationPresentationOptions.alert,
             UNNotificationPresentationOptions.sound,
             UNNotificationPresentationOptions.badge])
    }
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().apnsToken = deviceToken
    }
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        Messaging.messaging().subscribe(toTopic: "notice_push")
    }
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        
        let content = UNMutableNotificationContent()
        
        if let title = userInfo["title"]
        {
            content.title = title as! String
        }
        
        if let short_text = userInfo["short_text"]
        {
            content.body = short_text as! String
        } else if let short_text = userInfo["body"]
        {
            content.body = short_text as! String
        }
        
        if let badge = userInfo["badge"]
        {
            UIApplication.shared.applicationIconBadgeNumber = badge as! Int
        }
        //category = ".NoticeFullController";
        
        content.userInfo = userInfo
        content.sound = .default()
        content.threadIdentifier = "my-notice"
        if #available(iOS 12.0, *) {
            content.summaryArgument = "notification"
        } else {
            // Fallback on earlier versions
        }

        UNUserNotificationCenter.current().delegate = self
        let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 0.5, repeats: false)
        let request = UNNotificationRequest(identifier:"notice", content: content, trigger: trigger)

        UNUserNotificationCenter.current().add(request) { (error) in
            if let getError = error {
                print(getError.localizedDescription)
            }
        }

    }

}
  • Вопрос задан
  • 263 просмотра
Решения вопроса 1
@Wolfak Автор вопроса
Нашел решение в интернете:
Метод
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]

Устарел и его нужно удалить, поэтому нужно использовать:
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)

Если приложение на переднем плане, если приложение на заднем плане пуши получались и так используя код выше.
Обработка нажатия на уведомление:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    
        completionHandler()
        
    }
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы