当应用程序处于前台时获取本地通知 Swift 4 iOS 11

Jay*_*Jay 5 ios uilocalnotification swift

我想在我的应用程序处于前台时收到本地通知,当我尝试使用以下代码时,它永远不会触发通知,但是当我在后台输入应用程序时,它确实触发了。

这是我尝试过的:

//Schedule a Local Notification
func ScheduleNotification(timeInterval: Double, repeats: Bool, notificationBody:String, title:String){

    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: timeInterval, repeats: repeats)

    let center = UNUserNotificationCenter.current()

    let identifier = "UYLLocalNotification"
    let content = UNMutableNotificationContent()
    content.title = title
    content.body = notificationBody
    content.sound = UNNotificationSound.default()
    let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
    center.add(request, withCompletionHandler: { (error) in
        if let error = error {
            //Something went wrong
            print(error.localizedDescription)
        }
    })
}

override func viewDidLoad() {
    super.viewDidLoad()

    if Currentcount < data.count {
        self.ScheduleNotification(timeInterval: 5.0, repeats: false, notificationBody: "You have \(data.count - Currentcount) notification", title: "Alert!")
    }
}
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激谢谢。

nag*_*rrr 4

当您的应用程序位于前台时,该通知也可能会触发。

默认情况下,当通知到达并且目标应用程序位于前台时,iOS 不会显示任何 UI。显示通知内容是应用程序的工作。使用UNUserNotificationCenterDelegate您可以非常轻松地将通知显示为警报。请参阅这篇文章了解更多信息。