1

我可以在终止后生成本地通知但是,我无法在 UNUserNotificationCenterDelegate 的 didReceive 方法中设置值。

以下是我在 AppDelegate 中的代码:

class AppDelegate: UIResponder, UIApplicationDelegate{

    var window: UIWindow?
    let preferences = UserDefaults.standard
    let keyForTappingNotification = "notification_tapped"

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

        //Requesting Authorization for User Interactions
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in

        }

        return true
    }

}

以下是我在 ViewController 中的代码:

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

func userNotificationCenter(_ center: UNUserNotificationCenter,didReceive response: UNNotificationResponse,withCompletionHandler completionHandler: @escaping () -> Void) {
    preferences.set("yes", forKey: self.keyForTappingNotification)
    preferences.synchronize()

    completionHandler()
}

ViewdidLoad 如下:

override func viewDidLoad() {

        super.viewDidLoad()

        if let notification_tapped = self.preferences.string(forKey: self.keyForTappingNotification) {

            if notification_tapped.lowercased() == "yes"{
                //call to specific function which never gets called as values don't match
            }

        }
}

委托方法仅在应用程序处于前台或后台时接收响应,但在终止后不接收。

有没有办法在应用程序终止后接收响应?

4

0 回答 0