Pra*_*rma 2 iphone ios swift unusernotificationcenter
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()
}
}
Run Code Online (Sandbox Code Playgroud)
当应用程序从后台删除时,不会调用委托方法。请帮帮我
小智 6
将 UserNotifications 框架添加到项目时,需要检查以下 5 件事:
1) 如果您正在处理远程通知,请确保您已在 Xcode 项目的功能设置页面中启用它。
见图1
如果这给你带来了错误,你可能需要登录你的苹果开发者帐户并使用推送通知凭据创建一个密钥。最终结果为您提供了一个可供下载的 .p8 文件。创建此文件将清除错误。将推送通知发送到您的应用程序/设备的服务器上需要该文件本身。如果您需要这方面的帮助,请查看本教程。
2) 将导入行添加到 AppDelegate 文件的顶部
import UserNotifications
Run Code Online (Sandbox Code Playgroud)
3) 将 UNUserNotificationCenterDelegate 添加到您的 AppDelegate 类声明行。
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {...
Run Code Online (Sandbox Code Playgroud)
4) 在 application:didFinishLaunchingWithOptions 方法中将 UNUserNotificationCenter delegate 设置为 self。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//...
UNUserNotificationCenter.current().delegate = self
//...
return true
}
Run Code Online (Sandbox Code Playgroud)
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])
}
Run Code Online (Sandbox Code Playgroud)
希望有帮助。