你能让一个应用程序在打开时显示本地通知吗?

问题描述 投票:-1回答:1

我已经用UNUserNotificationCenter设置了通知,但它们只在应用程序不运行时才会显示。有一些较早的帖子问了同样的问题,但那些答案对我来说并不适用,所以我想知道是否有一个更新的方法来实现它。

ios swift uilocalnotification
1个回答
0
投票

下面的代码会触发 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])
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.