我正在尝试从我的 Mac 应用程序发送本地通知(使用 Cocoa 以 swift 编写) 到目前为止我已经编写了这个函数
func scheduleNotification() {
let content = UNMutableNotificationContent()
content.title = "Test"
content.body = "This is a test"
content.sound = .default
content.badge = 1
let now = Date()
let int = timePicker.dateValue.timeIntervalSince(now)
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: int, repeats: false)
let request = UNNotificationRequest(identifier: "Test notification", content: content, trigger: trigger)
center.add(request) { (err) in
if err == nil {
print("Success")
}
}
}
但由于某种原因,它在通知中心没有显示横幅或任何内容。是我的代码有问题还是其他原因导致了这种情况? (我查了一下,该应用有发送通知的权限)
另外,macOS 上的等效项是什么
iOS 上的 UIApplication.shared.applicationBadgeNumber = 0
?
最佳答案
如果应用程序位于前台,则必须使用 UNUserNotificationCenterDelegate。
UNUserNotificationCenter.current().delegate = self
首先在viewDidLoad中通知该委托(delegate)。
extension ViewController: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
return completionHandler([.alert, .sound, .badge])
}
}
然后你就可以像这样使用委托(delegate)了。查看此帖子的更多信息 -> Local Notifications
关于swift - 为什么 Mac 上不显示本地通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61634405/