在iOS应用中显示通知当应用程序在前景/活动在swift 3

yas*_*r h 0 push-notification apple-push-notifications ios swift

我正在尝试在应用处于活动状态时显示横幅通知.我使用了给定的方法但没有结果,横幅通知仅在应用关闭时出现:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    print("Push notification received: \(userInfo)")

    if application.applicationState == .active {
       print("active")
       let localNotification = UILocalNotification()
       localNotification.userInfo = userInfo
       localNotification.alertAction = "Test"
       localNotification.soundName = UILocalNotificationDefaultSoundName
       localNotification.alertBody = "Notification test!!"
       localNotification.fireDate = Date()
       UIApplication.shared.scheduleLocalNotification(localNotification)
     }
}
Run Code Online (Sandbox Code Playgroud)

它打印"活动"但通知未显示.我错过了任何一步吗?

谢谢.

Mus*_*ari 7

如果应用程序在前台运行,iOS将不会显示通知横幅/警报.您必须编写一些代码来处理应用程序在前台接收通知时的情况.

或者您可以使用流行的第三方库:github.com/bryx-inc/BRYXBanner

使用如下

import BRYXBanner // import in your class 

// Put this code where you are getting notification 
let banner = Banner(title: "title", subtitle: "subtitle", image: UIImage(named: "addContact"), backgroundColor: UIColor(red:137.0/255.0, green:172.0/255.0, blue:2.0/255.0, alpha:1.000))
banner.dismissesOnTap = true
banner.show(duration: 1.0)
Run Code Online (Sandbox Code Playgroud)

但是如果你正在使用iOS 10.0+那么你可以在应用程序处于前台时接近显示横幅消息的目标,使用以下方法.

 // This method will be called when app received push notifications in foreground for iOS 10+
 @available(iOS 10.0, *)
 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.alert, .badge, .sound])
 }
Run Code Online (Sandbox Code Playgroud)