gpt4 book ai didi

swift - 为什么我使用 UNUserNotificationCenter 创建的本地通知没有显示在屏幕的右上角?

转载 作者:行者123 更新时间:2023-12-03 17:37:31 25 4
gpt4 key购买 nike

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

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

来源:

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

最佳答案

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

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

关于swift - 为什么我使用 UNUserNotificationCenter 创建的本地通知没有显示在屏幕的右上角?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60050210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com