我正在使用Swift 4.2。当应用程序处于后台运行时,我会收到通知,但是当应用程序处于活动状态时,我不会收到通知。
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
我想知道如何在应用打开时得到通知
答案 0 :(得分:0)
您需要在AppDelegate类中确认UNUserNotificationCenterDelegate;
import UserNotifications
class AppDelegate : UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
}
然后您可以在ViewController类中调用此函数,不要忘记再次在ViewController中导入UserNotifications;
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
completionHandler([.alert, .badge, .sound])
}
答案 1 :(得分:0)
使用上述代码更新此代码
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler:
@escaping (UNNotificationPresentationOptions) -> Void) {
print("Handle push from foreground")
print("\(notification.request.content.userInfo)")
completionHandler([.alert, .badge, .sound])
return
}