用户希望通过点击推送通知进行交互并发送评论/回复/消息。
我在 AppDelegate 中有以下代码:
func configureNotification() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
center.delegate = notificationDelegate
let replyAction = UNTextInputNotificationAction(identifier: replyID, title: "Add reply", options: [], textInputButtonTitle: "Send", textInputPlaceholder: "Reply here")
let deafultCategory = UNNotificationCategory(identifier: "CustomSamplePush", actions: [replyAction], intentIdentifiers: [], options: [])
center.setNotificationCategories(Set([deafultCategory]))
UIApplication.shared.registerForRemoteNotifications()
}
并处理如下操作:
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let identifier = response.actionIdentifier
let request = response.notification.request
if identifier == replyID{
let textResponse = response as! UNTextInputNotificationResponse
let newContent = request.content.mutableCopy() as! UNMutableNotificationContent
newContent.body = textResponse.userText
addNotification(content: newContent, trigger: request.trigger, indentifier: request.identifier)
}
completionHandler()
}
func addNotification(content:UNNotificationContent,trigger:UNNotificationTrigger?, indentifier:String){
let request = UNNotificationRequest(identifier: indentifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: {
(errorObject) in
if let error = errorObject{
print("Error \(error.localizedDescription) in notification \(indentifier)")
}
})
}
仅供参考:此代码完美适用于 iOS 11 设备,但不适用于 iOS 13