|
| 1 | +// |
| 2 | +// AppDelegate.swift |
| 3 | +// TempBox (macOS) |
| 4 | +// |
| 5 | +// Created by Waseem Akram on 10/10/21. |
| 6 | +// |
| 7 | + |
| 8 | +import Foundation |
| 9 | +import SwiftUI |
| 10 | +import Resolver |
| 11 | +import Defaults |
| 12 | +import UserNotifications |
| 13 | + |
| 14 | +final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate { |
| 15 | + |
| 16 | + @Injected var persistenceManager: PersistenceManager |
| 17 | + |
| 18 | + func applicationDidFinishLaunching(_ notification: Notification) { |
| 19 | + registerNotifications() |
| 20 | + NSWindow.allowsAutomaticWindowTabbing = false |
| 21 | + if let mainMenu = NSApp.mainMenu { |
| 22 | + DispatchQueue.main.async { |
| 23 | + if let edit = mainMenu.items.first(where: { $0.title == "Edit"}) { |
| 24 | + mainMenu.removeItem(edit) |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + } |
| 30 | + |
| 31 | + func registerNotifications() { |
| 32 | + UNUserNotificationCenter.current().requestAuthorization( |
| 33 | + options: [.alert, .sound, .badge] |
| 34 | + ) { accepted, error in |
| 35 | + if let error = error { |
| 36 | + print(error) |
| 37 | + return |
| 38 | + } |
| 39 | + Defaults[.isNotificationsEnabled] = accepted |
| 40 | + if !accepted { |
| 41 | + print("Notification access denied.") |
| 42 | + } |
| 43 | + } |
| 44 | + UNUserNotificationCenter.current().delegate = self |
| 45 | + } |
| 46 | + |
| 47 | + func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { |
| 48 | + true |
| 49 | + } |
| 50 | + |
| 51 | + func applicationWillTerminate(_ notification: Notification) { |
| 52 | + persistenceManager.saveMainContext() |
| 53 | + } |
| 54 | + |
| 55 | + func userNotificationCenter(_ center: UNUserNotificationCenter, |
| 56 | + willPresent notification: UNNotification, |
| 57 | + withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { |
| 58 | + |
| 59 | + completionHandler([.banner, .list]) |
| 60 | + } |
| 61 | + |
| 62 | + func userNotificationCenter(_ center: UNUserNotificationCenter, |
| 63 | + didReceive response: UNNotificationResponse, |
| 64 | + withCompletionHandler completionHandler: @escaping () -> Void) { |
| 65 | + let categoryIdentifier = response.notification.request.content.categoryIdentifier |
| 66 | + if categoryIdentifier == "openFileFromLocation" { |
| 67 | + let userInfo = response.notification.request.content.userInfo |
| 68 | + |
| 69 | + if let fileLocation = userInfo["location"] as? String, let fileUrl = URL(string: fileLocation) { |
| 70 | + NSWorkspace.shared.open(fileUrl) |
| 71 | + } |
| 72 | + } |
| 73 | + completionHandler() |
| 74 | + } |
| 75 | + |
| 76 | +} |
0 commit comments