我试图理解为什么本地通知没有显示在前台。我相信我添加了所有正确的代码以实现此功能,但是当我的应用程序处于前台时,没有显示横幅。
这是我添加的内容AppDelegate.swift
:
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate
{
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
UNUserNotificationCenter.current().requestAuthorization(options: [UNAuthorizationOptions.alert, UNAuthorizationOptions.sound, UNAuthorizationOptions.badge]) { (willAllow: Bool, error: Error?) in
if willAllow == true
{
// Do something
}
}
UNUserNotificationCenter.current().delegate = self
// Override point for customization after application launch.
return true
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
print("GO IN HERE")
completionHandler(.alert)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
{
}
}
我的ViewController.swift
:
override func viewDidLoad()
{
super.viewDidLoad()
let content: UNMutableNotificationContent = UNMutableNotificationContent()
content.sound = UNNotificationSound.default()
content.subtitle = "This is a test"
let trigger: UNTimeIntervalNotificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request: UNNotificationRequest = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
当我的应用程序第一次启动时,我确实看到了允许我的应用程序推送通知的权限警报,但我根本看不到任何通知。
我确实看到了日志输出GO IN HERE,所以willPresent
被调用了。
还有什么我想念的吗?