如何让推送通知显示在通知中心?

6

这些内容都来自我目前正在开发的一个应用程序,我们称之为样例应用程序

如何从手机托盘中获取这些通知的列表

在此输入图片描述

是的,我确实知道可以使用以下代码获取通知:

if #available(iOS 10.0, *) {           
    UNUserNotificationCenter.current().getPendingNotificationRequests { (requests) in
        print("here are the iOS 10 notifs \(requests)")
    }         
} else {
    let requests = (UIApplication.shared.scheduledLocalNotifications ?? [])
    print("here are the NON iOS 10 notifs \(requests)")
}

但是这段代码的问题在于,我只能获得由我离线创建的通知,而不能获取来自苹果推送通知服务器(APNS)的通知。

所谓离线创建是指,预定的UILocalNotification,而由于推送通知不是UILocalNotification,所以我不知道该怎么办。

你可能会问的一些问题

  1. Are these notifications from my app?

    • Yes
  2. Am I using the didReceiveRemoteNotification on the AppDelegate?

    • Yes, but that's different.
  3. Does my remote notifications work/come from APNS

    • Yes.
  4. What does my code for registering remote notifications look like?

    if #available(iOS 10.0, *) {
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        let center = UNUserNotificationCenter.current()
        center.delegate = self
        center.requestAuthorization(options: authOptions, completionHandler: { (_, _) in })
    } else {
        let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }
    
    application.registerForRemoteNotifications()
    

1
为什么不使用 UNUserNotificationCenter.current.getDeliveredNotifications() 呢?另外,在 iOS 中并不存在所谓的“托盘”,您提到的应该是通知中心。 - Dávid Pásztor
更新答案并接受自己。 - Mathi Arasan
@user3589771 我还不能这样做,因为我仍然无法获取iOS 10以下设备的这些通知。 - Zonily Jame
如果没有其他方法获取通知,则低于iOS 10的设备可以使用NSUserDefault - Mathi Arasan
1个回答

5

Dávid Pásztor的评论部分解决了问题,因为现在我可以检索到在通知中心显示的所有(推送和非推送)通知,但仅适用于iOS 10,因为下面的代码仅适用于iOS 10及以上版本,那其他版本呢?

UNUserNotificationCenter.current().getDeliveredNotifications { (notifications) in
    print(notifications)
}

你好 @Zonily,你能否阅读其他应用的推送通知,例如Instagram和iMessage,或者只能接收来自你的应用程序的通知? - stackich
@stackich 不可能读取其他应用程序的通知。 - Chirag Kalsariya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接