iOS推送通知操作按钮不显示

时间:2018-03-03 14:00:28

标签: ios swift push-notification

我正在尝试为推送通知添加操作按钮。实际上,它是在我构建应用程序时成功添加并首次授予通知权限。

问题在我杀死应用程序并尝试再次发送通知后开始。通知正在接收,但不显示操作按钮。我想我没有在正确的位置定义setNotificationCategories()方法,但我找不到正确的解决方案。这是我的代码:(感谢您的帮助)

的AppDelegate:

import UIKit
import UserNotifications


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate{

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) {(granted, error) in
            if !granted {
                print("Notification access denied.")
            }
            setNotificationCategory()
        }

        if #available(iOS 10.0, *) {
            setNotificationCategory()
            UNUserNotificationCenter.current().delegate = self
        }

        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
    }

    func applicationWillTerminate(_ application: UIApplication) {
    }
}

@available(iOS 10.0, *)
extension AppDelegate: UNUserNotificationCenterDelegate{

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        if response.notification.request.content.categoryIdentifier == Constants.Notification.Category.general{
            if response.actionIdentifier == Constants.Notification.Action.likeAction{
                if let notificationID = response.notification.request.content.userInfo["notification_id"]{
                    NotificationActionHandler.likeActionHandler(notificationID: notificationID as! Int)
                }
            }

        }

        completionHandler()
    }

    func setNotificationCategory(){
        let likeAction = UNNotificationAction(identifier: Constants.Notification.Action.likeAction, title: "❤️", options: [])
        let generalCategory = UNNotificationCategory(identifier: Constants.Notification.Category.general, actions: [likeAction], intentIdentifiers: [], options: .customDismissAction)
        let center = UNUserNotificationCenter.current()
        center.setNotificationCategories([generalCategory])
    }
}

NotificationActionHandler:

import Foundation

class NotificationActionHandler{

    class func likeActionHandler(notificationID: Int){
        print("liked! ❤️ \(notificationID)")
    }
}

0 个答案:

没有答案