Можете ли вы заставить приложение отображать локальное уведомление, пока оно открыто? - PullRequest
0 голосов
/ 01 мая 2020

Я настроил уведомления с помощью UNUserNotificationCenter, но они отображаются только тогда, когда приложение не запущено. Есть некоторые старые темы, задающие тот же вопрос, но ответы на них не работают для меня, поэтому мне интересно, есть ли обновленный способ сделать это.

1 Ответ

0 голосов
/ 01 мая 2020

Приведенный ниже код запускает local notification, когда приложение находится на переднем и заднем плане.

import UIKit
import UserNotifications

class ViewController: UIViewController, UNUserNotificationCenterDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        //requesting for authorization
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in
                if error == nil {
                    self.triggerLocalNotification()
            }
        })
    }

    func triggerLocalNotification(){

        //creating the notification content
        let content = UNMutableNotificationContent()

        //adding title, subtitle, body and badge
        content.title = "Notification title "
        content.subtitle = "Notification sub-title "
        content.body = "We are learning about iOS Local Notification"
        content.badge = 1

        //it will be called after 5 seconds
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

        //getting the notification request
        let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)

        UNUserNotificationCenter.current().delegate = self

        //adding the notification to notification center
        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        //displaying the ios local notification when app is in foreground
        completionHandler([.alert, .badge, .sound])
    }
}
...