iOS critical alert through FCM

后端 未结 2 2103
别跟我提以往
别跟我提以往 2021-01-15 06:08

iOS 12 has added critical alerts. The APNS payload has the sound dictionary to support critical alerts. Is there an equivalent sound dictionary support in FCM payload to sen

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-15 06:41

    Answering my own question.

    I had to rely on notification extension to do the magic as the FCM payload doesn't support the iOS sound dictionary. I send the "critical" flag set to 1 as part of FCM data payload and use it in notification extension to mark a notification as critical.

    class NotificationService: UNNotificationServiceExtension {
        var contentHandler: ((UNNotificationContent) -> Void)?
        var bestAttemptContent: UNMutableNotificationContent?
    
        override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
           self.contentHandler = contentHandler
           bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
           let userInfo: [AnyHashable : Any] = (bestAttemptContent?.userInfo)!
           if let apsInfo = userInfo["aps"] as? [AnyHashable: Any], let bestAttemptContent = bestAttemptContent, let critical =  userInfo["critical"] as? String, Int(critical)! == 1 {
                //critical alert try to change the sound if sound file is sent in notificaiton.
                if let sound = apsInfo["sound"] as? String {
                    //sound file is present in notification. use it for critical alert..
                    bestAttemptContent.sound =
                        UNNotificationSound.criticalSoundNamed(UNNotificationSoundName.init(sound),
                                                               withAudioVolume: 1.0)
                } else {
                    //sound file not present in notifiation. use the default sound.
                    bestAttemptContent.sound =
                                    UNNotificationSound.defaultCriticalSound(withAudioVolume: 1.0)
                }
                contentHandler(bestAttemptContent)
            }
        }
    }
    

提交回复
热议问题