利用SilentNotification实现PushNotification定制

苹果的PushNotification功能本身支持一定程度的定制,从而实现对国语言的支持。
Ref: Localizing the Content of Your Remote Notifications

然而,如果希望对消息进行完全的定制,决定是否显示,内容的修改等等,则需要通过
SilentNotification (即Background RemoteNotification)的后台处理实现。

原理

  1. 当Notification中含有content-avalible字段时,可以不包含title等用于显示通知的字段,这样用户就不会看到系统通知(SilentNotification)
  2. 含有content-avalible字段的通知会触发didReceiveRemoteNotification回掉,应用程序有一定时间执行后台代码(包括网络等IO操作)
  3. 在处理代码中根据Notification的自定义字段,创建本地的通知并显示

具体实现

准备工作

  1. 配置APNs相关设置和证书(同普通的PushNotification)
  2. 在Xcode Target - Capabilities 中开启 BackgroundModes - Remote notification 选项

实现回掉和自定义消息显示

didReceiveRemoteNotification中调用

func handleCustomRemoteNotification(userInfo: [AnyHashable : Any]) {
        if userInfo["custom_show"] == nil || userInfo["custom_show"] as? Bool == false {
            return
        }
        // ios 10:用UNNotificationRequest代替
        let noti = UILocalNotification()
        noti.alertTitle = userInfo["custom_title"] as? String
        noti.alertBody = userInfo["custom_body"] as? String
        UIApplication.shared.scheduleLocalNotification(noti)
}

发送消息

这里调用的是FirebaseCloudMessage的API(别的方法调用APNs同理):

{
   "registration_ids": [
   "dxqsNKgd:ABC"],
   "content_available":true,
   "data": {
   	 "custom_show":true,
   	 "custom_title":"TITLE",
   	 "custom_body":"BODY"
   },
    "priority":"high"
}

总结

利用SilentNotification实现PushNotification定制的好处:

  • 对PushNotification的自定义处理和显示
  • 可以指定时间/延时显示Notification

不足之处:

  • 用户强制退出应用后,SilentNotification无法使用
  • 额外的通知Payload,处理代码
comments powered by Disqus