feature: adapt new UserNotifications api for send notification

This commit is contained in:
yicheng 2021-10-04 16:22:46 +08:00
parent 1d92df796b
commit 2d46b2816f
No known key found for this signature in database
GPG Key ID: 7CF411A6623B1C0A
2 changed files with 121 additions and 26 deletions

View File

@ -459,7 +459,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
if let error = err {
NSUserNotificationCenter.default
.post(title: NSLocalizedString("Reload Config Fail", comment: ""),
.postNotificationAlert(title: NSLocalizedString("Reload Config Fail", comment: ""),
info: error)
} else {
self.syncConfig()

View File

@ -7,73 +7,168 @@
//
import Cocoa
import UserNotifications
extension NSUserNotificationCenter {
func post(title: String, info: String, identifier: String? = nil) {
let notification = NSUserNotification()
notification.title = title
notification.informativeText = info
if identifier != nil {
notification.userInfo = ["identifier": identifier!]
if #available(OSX 10.14, *) {
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = UserNotificationCenterDelegate.shared
notificationCenter.getNotificationSettings {
[weak self] settings in
switch settings.authorizationStatus {
case .denied:
DispatchQueue.main.async {
self?.postNotificationAlert(title: title, info: info, identifier: identifier)
}
case .authorized, .provisional:
DispatchQueue.main.async {
self?.postNotification(title: title, info: info, identifier: identifier)
}
case .notDetermined:
notificationCenter.requestAuthorization(options: .alert) { granted, err in
if granted {
DispatchQueue.main.async {
self?.postNotification(title: title, info: info, identifier: identifier)
}
} else {
DispatchQueue.main.async {
self?.postNotificationAlert(title: title, info: info, identifier: identifier)
}
}
}
@unknown default:
DispatchQueue.main.async {
self?.postNotification(title: title, info: info, identifier: identifier)
}
}
}
} else {
postNotification(title: title, info: info, identifier: identifier)
}
delegate = UserNotificationCenterDelegate.shared
deliver(notification)
}
private func postNotification(title: String, info: String, identifier: String? = nil) {
var userInfo:[String : Any] = [:]
if let identifier = identifier {
userInfo = ["identifier": identifier]
}
if #available(OSX 10.14, *) {
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = UserNotificationCenterDelegate.shared
notificationCenter.removeAllDeliveredNotifications()
notificationCenter.removeAllPendingNotificationRequests()
let content = UNMutableNotificationContent();
content.title = title
content.body = info
content.userInfo = userInfo
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: nil)
notificationCenter.add(request) { error in
if let err = error {
Logger.log("send noti fail: \(String(describing: err))")
DispatchQueue.main.async {
self.postNotificationAlert(title: title, info: info, identifier: identifier)
}
}
}
} else {
let notification = NSUserNotification()
notification.title = title
notification.informativeText = info
notification.userInfo = userInfo
delegate = UserNotificationCenterDelegate.shared
deliver(notification)
}
}
func postNotificationAlert(title: String, info: String, identifier: String? = nil) {
let alert = NSAlert()
alert.messageText = title
alert.informativeText = info
alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
alert.runModal()
if let identifier = identifier {
UserNotificationCenterDelegate.shared.handleNotificationActive(with: identifier)
}
}
func postConfigFileChangeDetectionNotice() {
post(title: NSLocalizedString("Config file have been changed", comment: ""),
info: NSLocalizedString("Tap to reload config", comment: ""),
identifier: "postConfigFileChangeDetectionNotice")
}
func postStreamApiConnectFail(api: String) {
post(title: "\(api) api connect error!",
info: NSLocalizedString("Use reload config to try reconnect.", comment: ""))
}
func postConfigErrorNotice(msg: String) {
let configName = ConfigManager.selectConfigName.count > 0 ?
Paths.configFileName(for: ConfigManager.selectConfigName) : ""
Paths.configFileName(for: ConfigManager.selectConfigName) : ""
let message = "\(configName): \(msg)"
post(title: NSLocalizedString("Config loading Fail!", comment: ""), info: message)
postNotificationAlert(title: NSLocalizedString("Config loading Fail!", comment: ""), info: message)
}
func postSpeedTestBeginNotice() {
post(title: NSLocalizedString("Benchmark", comment: ""),
info: NSLocalizedString("Benchmark has begun, please wait.", comment: ""))
}
func postSpeedTestingNotice() {
post(title: NSLocalizedString("Benchmark", comment: ""),
info: NSLocalizedString("Benchmark is processing, please wait.", comment: ""))
}
func postSpeedTestFinishNotice() {
post(title: NSLocalizedString("Benchmark", comment: ""),
info: NSLocalizedString("Benchmark Finished!", comment: ""))
}
func postProxyChangeByOtherAppNotice() {
post(title: NSLocalizedString("System Proxy Changed", comment: ""),
info: NSLocalizedString("Proxy settings are changed by another process. ClashX is no longer the default system proxy.", comment: ""))
}
}
class UserNotificationCenterDelegate: NSObject, NSUserNotificationCenterDelegate {
class UserNotificationCenterDelegate: NSObject, NSUserNotificationCenterDelegate, UNUserNotificationCenterDelegate {
static let shared = UserNotificationCenterDelegate()
func userNotificationCenter(_ center: NSUserNotificationCenter, didActivate notification: NSUserNotification) {
switch notification.userInfo?["identifier"] as? String {
if let identifier = notification.userInfo?["identifier"] as? String {
handleNotificationActive(with: identifier)
}
center.removeAllDeliveredNotifications()
}
func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool {
return true
}
@available(macOS 10.14, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if let identifier = response.notification.request.content.userInfo["identifier"] as? String {
handleNotificationActive(with: identifier)
}
center.removeAllDeliveredNotifications()
completionHandler()
}
@available(macOS 10.14, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(.alert)
}
func handleNotificationActive(with identifier: String) {
switch identifier {
case "postConfigFileChangeDetectionNotice":
AppDelegate.shared.updateConfig()
center.removeAllDeliveredNotifications()
default:
break
}
}
func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool {
return true
}
}