ios - 应用程序终止时未调用 UNUserNotificationCenter didReceive 响应

标签 ios swift unusernotificationcenter

我正在处理本地通知,但我遇到的问题是当应用程序终止时没有调用 didReceive Response 方法,所以当我点击通知操作时它只是启动应用程序而没有做任何其他事情。但是,当该应用程序仅在后台运行时,一切正常。我的代码有什么问题吗?

//MyClassNameViewController.swift

override func viewDidLoad() {
    super.viewDidLoad()

    UNUserNotificationCenter.current().delegate = self

}

func triggerAlarm1() {
    // Create an instance of notification center
    let center = UNUserNotificationCenter.current()

    // Sets the details of the notification
    let content = UNMutableNotificationContent()
    content.title = "Recorded Today's first alarm."
    content.body = "Be completely honest: how is your day so far?"
    content.sound = UNNotificationSound.default()
    content.categoryIdentifier = "notificationID1"

    // Set the notification to trigger everyday
    let triggerDaily = Calendar.current.dateComponents([.hour,.minute], from: myTimePicker1.date)
    let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)

    // Deliver the notification
    let identifier = "UYLLocalNotification"
    let request = UNNotificationRequest(identifier: identifier,
                                        content: content, trigger: trigger)
    center.add(request, withCompletionHandler: { (error) in
        if error != nil {
            // Just in case something went wrong
            print(error!)
        }
    })

}

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

    print("didReceive Method called")

    if response.actionIdentifier == "actionOne" {
        let alertOne = UIAlertController(title: "First", message: "Some Message Here", preferredStyle: UIAlertControllerStyle.alert)
        let actionOne = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
        alertOne.addAction(actionOne)
        self.present(alertOne, animated: true, completion: nil)
    }
    completionHandler()
}

//AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    UNUserNotificationCenter.current().delegate = self

    // Request Authorisation
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert , .sound , .badge]) { (Bool, error) in
        // insert code here
    }

    let actionOne = UNNotificationAction(identifier: "actionOne", title: "Open1", options: [.foreground])
    let catogeryOne = UNNotificationCategory(identifier: "notificationID1", actions: [actionOne], intentIdentifiers: [], options: [])
    UNUserNotificationCenter.current().setNotificationCategories([catogeryOne])

    return true
}

最佳答案

在你的 Action 标识符中调用这个函数,你会没事的!

 func alertAction() {

    let alertController = UIAlertController(title: "Hello", message: "This is cool!", preferredStyle: .alert)
    alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in
        // Do something with handler block
    }))

    let pushedViewControllers = (self.window?.rootViewController as! UINavigationController).viewControllers
    let presentedViewController = pushedViewControllers[pushedViewControllers.count - 1]

    presentedViewController.present(alertController, animated: true, completion: nil)
}

super 简单!

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

    print("didReceive Method called")

    if response.actionIdentifier == "actionOne" {
        DispatchQueue.main.async(execute: {
            self.alertAction()
        })
    } else if response.actionIdentifier == "actionTwo" {

    } else if response.actionIdentifier == "actionThree" {

    }
    completionHandler()
}

完全适用于 Swift 3.0 和 Xcode 8.0。我已经更改了 View Controller 之间的所有连接。我在初始的 ViewController 中添加了一个 NavigationController

Change the connections to the <code>show</code> instead of the <code>present modally</code>

应用委托(delegate):

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.


    let center = UNUserNotificationCenter.current()
    center.delegate = self

    // Request Authorisation
    center.requestAuthorization(options: [.alert , .sound , .badge]) { (Bool, error) in
        // insert code here
    }

    let actionOne = UNNotificationAction(identifier: "actionOne", title: "Open1", options: [.foreground])
    let catogeryOne = UNNotificationCategory(identifier: "notificationID1", actions: [actionOne], intentIdentifiers: [], options: [])

    let actionTwo = UNNotificationAction(identifier: "actionTwo", title: "Open2", options: [.foreground])
    let catogeryTwo = UNNotificationCategory(identifier: "notificationID2", actions: [actionTwo], intentIdentifiers: [], options: [])

    let actionThree = UNNotificationAction(identifier: "actionThree", title: "Open3", options: [.foreground])
    let catogeryThree = UNNotificationCategory(identifier: "notificationID3", actions: [actionThree], intentIdentifiers: [], options: [])

    UNUserNotificationCenter.current().setNotificationCategories([catogeryOne, catogeryTwo, catogeryThree])

    return true
}


func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    print("willPresent method called")
    completionHandler([.alert, .sound])
}

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

    print("didReceive Method called")

    if response.actionIdentifier == "actionOne" {
        DispatchQueue.main.async(execute: {
            self.alertAction()
        })
    } else if response.actionIdentifier == "actionTwo" {

    } else if response.actionIdentifier == "actionThree" {

    }
    completionHandler()
}



func alertAction() {

    let alertController = UIAlertController(title: "Hello", message: "This is cool!", preferredStyle: .alert)
    alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in
        // Do something with handler block
    }))

    let pushedViewControllers = (self.window?.rootViewController as! UINavigationController).viewControllers
    let presentedViewController = pushedViewControllers[pushedViewControllers.count - 1]

    presentedViewController.present(alertController, animated: true, completion: nil)
}

我还从 viewDidLoad 和其他地方删除了所有以前的建议。

enter image description here

将您的连接更改为 show 并且不要以模态方式呈现。如果您想在任何地方显示您的警报。祝你好运

关于ios - 应用程序终止时未调用 UNUserNotificationCenter didReceive 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42050324/

相关文章:

ios - 从 AppDelegate 通知 View Controller 的正确方法是什么?

ios - 本地化从 Firebase 发送的通知

ios - 更改高度时如何在单元格中显示标签 View 的全文

ios - 适用于 iOS 5 的地理围栏 API

ios - 使用 Xcode 将预加载的 sqlite 数据库添加到 iOS 应用程序后找不到表

ios - 如何使用 swift 4.2 按名称字段在 viewDidload 和搜索选项中执行可编码值?

ios - 再次发送通知

swift - 从 TabBarController 呈现一个特定的 ViewController

ios - App Store发行国家/地区

ios JASidePanels 使 UINavigationController 成为 centerViewController