UNUserNotificationCenterDelegate
从后台删除时不起作用。当应用程序停留在前景和背景中时,它工作正常。
这里是代码
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let rootViewController = self.window!.rootViewController as! UINavigationController
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let profileViewController = mainStoryboard.instantiateViewController(withIdentifier: "SampleViewController") as! SampleViewController
rootViewController.pushViewController(profileViewController, animated: true)
completionHandler()
}
}
从后台删除应用程序时,未调用方法。请帮帮我
答案 0 :(得分:1)
将UserNotifications框架添加到项目中时,需要检查以下5件事:
1)如果要处理远程通知,请确保已在Xcode项目的功能设置页面中启用了该功能。
请参见figure 1
如果这给您带来错误,则可能需要登录到Apple开发人员帐户并使用推送通知凭据创建密钥。最终结果为您提供一个.p8文件进行下载。创建此文件将清除错误。在将推送通知发送到您的应用程序/设备的服务器上,文件本身是必需的。如果您需要帮助,请查看此tutorial。
2)将导入行添加到AppDelegate文件的顶部
import UserNotifications
3)将UNUserNotificationCenterDelegate添加到您的AppDelegate类声明行。
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {...
4)在application:didFinishLaunchingWithOptions方法中将UNUserNotificationCenter委托设置为self。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//...
UNUserNotificationCenter.current().delegate = self
//...
return true
}
5)添加您的委托函数(如果您想使用它们)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
NSLog("Application delegate method userNotificationCenter:didReceive:withCompletionHandler: is called with user info: %@", response.notification.request.content.userInfo)
//...
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
NSLog("userNotificationCenter:willPresent")
//...
completionHandler([.alert])
}
希望有帮助。
答案 1 :(得分:0)
检查didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]?
方法。当用户点击通知横幅(并且该应用终止)时,该应用将启动,该方法将被调用,并且launchOptions
包含通知信息。因此,您可以通过点击通知横幅来了解(通过检查launchOptions
)该应用程序已启动,并导航到您想要的用户