为什么我的 userNotificationCenter 在被解雇时没有收到 运行
Why my userNotificationCenter didReceive not run when fired
我使用 UserNotifications 做一个简单的通知来测试,我在 AppDelegate 中写了如下代码,当通知在后台触发时,它会在屏幕上显示消息,但它没有 运行代码 print(...) 和 a.get()) :
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("run in didReceive")
let a = ViewController()
a.get()
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge, .carPlay], completionHandler: { (granted, error) in
if granted {
print("granted")
}else{
print("not granted")
}
})
UNUserNotificationCenter.current().delegate = self
return true
}
我只想运行一个"viewcontroller"函数当应用程序在后台时...
这一行有一个问题:
let a = ViewController()
您正在创建一个 "loose" 视图控制器,然后将其丢弃。您可能想要的是对某些现有视图控制器的引用,该视图控制器在界面中已经。
一个更广泛的问题可能是关于 userNotificationCenter(_:didReceive:withCompletionHandler:)
的用途的错误假设。它不会被调用以指示出现通知警报(即触发通知)。调用它是为了表明 用户与通知进行了交互 ,例如点击或(如果已配置)解除警报。在没有用户交互的情况下刚出现又消失的横幅警报不会导致调用 userNotificationCenter(_:didReceive:withCompletionHandler:)
。
我使用 UserNotifications 做一个简单的通知来测试,我在 AppDelegate 中写了如下代码,当通知在后台触发时,它会在屏幕上显示消息,但它没有 运行代码 print(...) 和 a.get()) :
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("run in didReceive")
let a = ViewController()
a.get()
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge, .carPlay], completionHandler: { (granted, error) in
if granted {
print("granted")
}else{
print("not granted")
}
})
UNUserNotificationCenter.current().delegate = self
return true
}
我只想运行一个"viewcontroller"函数当应用程序在后台时...
这一行有一个问题:
let a = ViewController()
您正在创建一个 "loose" 视图控制器,然后将其丢弃。您可能想要的是对某些现有视图控制器的引用,该视图控制器在界面中已经。
一个更广泛的问题可能是关于 userNotificationCenter(_:didReceive:withCompletionHandler:)
的用途的错误假设。它不会被调用以指示出现通知警报(即触发通知)。调用它是为了表明 用户与通知进行了交互 ,例如点击或(如果已配置)解除警报。在没有用户交互的情况下刚出现又消失的横幅警报不会导致调用 userNotificationCenter(_:didReceive:withCompletionHandler:)
。