Swift

Swift – UserNotifications框架使用详解5(Actionable可交互通知)

import UIKit
import UserNotifications
 
//通知category标识符枚举
enum NotificationCategory: String {
    case news  //新闻资讯通知category
}
 
//通知category的action标识符枚举
enum NotificationCategoryAction: String {
    case like
    case cancel
    case comment
}
 
//通知响应对象
class NotificationHandler: NSObject, UNUserNotificationCenterDelegate {
    //对通知进行响应(用户与通知进行交互时被调用)
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler:
        @escaping () -> Void) {
        //根据category标识符做相应的处理
        let categoryIdentifier = response.notification.request.content.categoryIdentifier
        if let category = NotificationCategory(rawValue: categoryIdentifier) {
            switch category {
            case .news:
                handleNews(response: response)
            }
        }
        completionHandler()
    }
     
    //处理新闻资讯通知的交互
    private func handleNews(response: UNNotificationResponse) {
        let message: String
         
        //判断点击是那个action
        if let actionType = NotificationCategoryAction(rawValue: response.actionIdentifier) {
            switch actionType {
            case .like: message = "你点击了“点个赞”按钮"
            case .cancel: message = "你点击了“取消”按钮"
            case .comment:
                message = "你输入的是:\((response as! UNTextInputNotificationResponse).userText)"
            }
        } else {
            //直接点击通知,或者点击删除这个通知会进入这个分支。
            message = ""
        }
         
        //弹出相关信息
        if !message.isEmpty {
            showAlert(message: message)
        }
    }
     
    //在根视图控制器上弹出普通消息提示框
    private func showAlert(message: String) {
        if let vc = UIApplication.shared.keyWindow?.rootViewController {
            let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "确定", style: .cancel))
            vc.present(alert, animated: true)
        }
    }
}
mport UIKit
import UserNotifications
 
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
     
    var window: UIWindow?
     
    let notificationHandler = NotificationHandler()
     
    func application(_ application: UIApplication, didFinishLaunchingWithOptions
        launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        //请求通知权限
        UNUserNotificationCenter.current()
            .requestAuthorization(options: [.alert, .sound, .badge]) {
                (accepted, error) in
                if !accepted {
                    print("用户不允许消息通知。")
                }
        }
         
        //注册category
        registerNotificationCategory()
        UNUserNotificationCenter.current().delegate = notificationHandler
         
        return true
    }
     
    func applicationWillResignActive(_ application: UIApplication) {
    }
     
    func applicationDidEnterBackground(_ application: UIApplication) {
    }
     
    func applicationWillEnterForeground(_ application: UIApplication) {
    }
     
    func applicationDidBecomeActive(_ application: UIApplication) {
    }
     
    func applicationWillTerminate(_ application: UIApplication) {
    }
     
    //注册一个category
    private func registerNotificationCategory() {
        let newsCategory: UNNotificationCategory = {
            //创建输入文本的action
            let inputAction = UNTextInputNotificationAction(
                identifier: NotificationCategoryAction.comment.rawValue,
                title: "评论",
                options: [.authenticationRequired],
                textInputButtonTitle: "发送",
                textInputPlaceholder: "在这里留下你想说的话...")
             
            //创建普通的按钮action
            let likeAction = UNNotificationAction(
                identifier: NotificationCategoryAction.like.rawValue,
                title: "点个赞",
                options: [.foreground])
             
            //创建普通的按钮action
            let cancelAction = UNNotificationAction(
                identifier: NotificationCategoryAction.cancel.rawValue,
                title: "取消",
                options: [.destructive])
             
            //创建category
            return UNNotificationCategory(identifier: NotificationCategory.news.rawValue,
                                          actions: [inputAction, likeAction, cancelAction],
                                          intentIdentifiers: [], options: [.customDismissAction])
        }()
         
        //把category添加到通知中心
        UNUserNotificationCenter.current().setNotificationCategories([newsCategory])
    }
}
import UIKit
import UserNotifications
 
class ViewController: UIViewController {
     
    override func viewDidLoad() {
        super.viewDidLoad()
         
        //设置推送内容
        let content = UNMutableNotificationContent()
        content.title = "hangge.com"
        content.body = "囤积iPhoneX的黄牛赔到怀疑人生?"
        //设置通知对应的category标识符
        content.categoryIdentifier = NotificationCategory.news.rawValue
         
        //设置通知触发器
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
         
        //设置请求标识符
        let requestIdentifier = "com.hangge.testNotification"
         
        //设置一个通知请求
        let request = UNNotificationRequest(identifier: requestIdentifier,
                                            content: content, trigger: trigger)
         
        //将通知请求添加到发送中心
        UNUserNotificationCenter.current().add(request) { error in
            if error == nil {
                print("Time Interval Notification scheduled: \(requestIdentifier)")
            }
        }
    }
     
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
{
  "aps":{
    "alert":{
      "title":"hangge.com",
      "body":"囤积iPhoneX的黄牛赔到怀疑人生?"
    },
    "sound":"default",
    "badge":1,
    "category":"news"
  }
}