我目前正在尝试将Notification Service Extension
用作在push notification payload
. 为了解决这个问题,我想我会创建一个通知服务扩展来跟踪已收到的消息数量,并相应地跟踪计数。上周我得到了这个工作,现在我继续它,它不再工作了,我不知道为什么会这样。
Notification Service Extension
捆绑 ID 正在根据目标进行更改。对于我拥有的 2 个目标,此预构建脚本看起来像这样
buildID=${PRODUCT_BUNDLE_IDENTIFIER}
extId="AppPushNotification"
/usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier $buildID.$extId" "${SRCROOT}/${extId}/Info.plist"
我在扩展程序中使用的代码
import UIKit
import UserNotifications
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)
if let bestAttemptContent = bestAttemptContent {
// Modify the notification content here...
let userDefaults = UserDefaults.init(suiteName: "group.com.my.bundle.notification-service-extension")
let unreadMessages = userDefaults?.integer(forKey: "unreadMessages")
let newUnreadMessages = unreadMessages != nil ? unreadMessages! + 1 : 0
bestAttemptContent.title = "\(bestAttemptContent.title) [modified]"
bestAttemptContent.badge = NSNumber(value: newUnreadMessages)
let userInfo = bestAttemptContent.userInfo
guard let info = userInfo["aps"] as? [AnyHashable: Any],
let data = info["data"] as? [AnyHashable: Any],
let chatId = data["chatId"] as? String else { return }
let unreadMessagesInChat = userDefaults?.integer(forKey: chatId)
let newUnreadMessagesInChat = unreadMessagesInChat != nil ? unreadMessagesInChat! + 1 : 0
userDefaults?.set(newUnreadMessages, forKey: "unreadMessages")
userDefaults?.set(newUnreadMessagesInChat, forKey: chatId)
contentHandler(bestAttemptContent)
}
}
override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
}
我正在使用Pusher
. 我发送的有效载荷:
{
"aps":{
"mutalbe-content":1,
"content-available":1,
"sound":"true",
"alert":{
"title":"Vera Pauw",
"body":"test bericht"
},
"data":{
"type":"test",
"message":"test bericht",
"chatId":"3b002aa6-1117-4206-b54f-8bc2bd689f1c",
"fromId":"",
"fromname":"Vera Pauw"
}
}
}
我成功收到通知,但它不会触发扩展代码。我尝试过多种方式进行调试,比如在运行应用程序后选择调试目标,或者从扩展目标运行应用程序但进程Notification Service
总是说Waiting to Attach
. 我尝试过使用我的推送通知有效负载,但这并没有改变结果。
有谁知道为什么会发生这种情况或我哪里出错了。