我正在为IOS应用程序设计推送通知系统。我要满足一些要求。
能够在本地更改推送的标题和正文。
让通知中心仅按标识符显示最新通知。因此,如果设备收到2个具有相同标识符的推送通知请求,则第二个应替换通知中心中的第一个。
即使在强行终止应用程序的情况下也能够发送推送。
使用UNNotificationServiceExtension
在使用ServiceExtension时,我可以修改内容,但不能更改请求标识符,因为它是仅获取属性。因此,我的通知中心不会将旧的通知替换为新的通知。
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
if var bestAttemptContent = bestAttemptContent {
// Modify the notification content here... sweet!
bestAttemptContent.title = "\(bestAttemptContent.title) [modified]"
//resolveNotificationContent(content: &bestAttemptContent)
//getDeliveredNotifications always returns an empty array of notifications
UNUserNotificationCenter.current().getDeliveredNotifications{ notifications in
print("notifications: \(notifications)")
}
contentHandler(bestAttemptContent)
}
}
使用静默通知
我的另一个想法是发送静默通知,并像这样手动在本地创建“非静默”通知。
//Called when the user recieves a notifiation and the app is in the background
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
log.info()
defer {
completionHandler(.noData)
}
//if app is active, return
if application.applicationState == .active {
return
}
guard let content = PushNotification.createNotificationContent(from: userInfo) else {
return
}
guard let notificationData = content.userInfo["data"] as? [String: Any] else {
log.error("failed to convert 'aps' value to Dict<String:Any>")
return
}
let pushData = PushNotification.resolveNotification(from: notificationData)
var identifier = ""
if pushData != nil {
identifier = pushData!.getIdentifier()
}
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request) { (error) in
self.log.error(error)
}
}
问题是当应用被强行终止(有意义)时,我的静默通知从不发送。
有什么办法可以满足所有3个要求?