本文介绍了为什么我用UNUserNotificationCenter创建的本地通知没有显示在屏幕的右上角?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行下面的代码不会在屏幕的右上角显示通知(作为横幅或警报).通知显示在通知中心.

Running the code below doesn't show the notification in the upper-right corner of my screen (as a banner or alert). The notification is shown in the notification center.

我确保在我的系统上禁用了请勿打扰".我还尝试了系统偏好设置"->通知"->我的应用程序名称"中的横幅"和警报"设置.

I made sure "Do not disturb" is disabled on my system. I also tried both the "Banner" and "Alert" setting in System Preferences -> Notifications -> Name of my app.

来源:

import Cocoa
import UserNotifications

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        let notificationCenter = UNUserNotificationCenter.current()
        notificationCenter.requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
            print("requestNotificationAuthorization: granted=\(granted) error=\(String(describing: error))")
        }


        let content = UNMutableNotificationContent()
        content.title = "bar"
        content.body = "foo"
        content.categoryIdentifier = "alarm"

        let uuidString = UUID().uuidString

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 2, repeats: false)

        let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger)

        notificationCenter.add(request, withCompletionHandler: { error in
            print("completion handler called")
            if error != nil {
                print("notification center error: \(String(describing: error))")
            }
        })
    }

    func applicationWillTerminate(_ aNotification: Notification) {
    }
}

控制台输出:

requestNotificationAuthorization: granted=true error=nil
completion handler called

推荐答案

如果您希望在应用程序处于前台时看到通知横幅,请使用以下方法

if you want to see notification banner while app is in foreground use below method

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        // Forground notifications.
        completionHandler([.alert, .sound])
    }

这篇关于为什么我用UNUserNotificationCenter创建的本地通知没有显示在屏幕的右上角?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 04:52