Skip to content

Instantly share code, notes, and snippets.

@notoroid
Last active August 4, 2022 05:17
Show Gist options
  • Save notoroid/5e594216feef65ee0980dab9b0f82051 to your computer and use it in GitHub Desktop.
Save notoroid/5e594216feef65ee0980dab9b0f82051 to your computer and use it in GitHub Desktop.
import SwiftUI
import UserNotifications
#if os(iOS)
class AppDelegate : UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
registerForPushNotifications()
UNUserNotificationCenter.current().delegate = self
return true
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
// Enabled in the foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
[.badge , .banner, .sound]
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
// reset app badge
UIApplication.shared.applicationIconBadgeNumber = 0
}
}
#endif
#if os(macOS)
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
registerForPushNotifications()
UNUserNotificationCenter.current().delegate = self
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
// Enabled in the foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
[.badge , .banner, .sound]
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
// reset app badge
await MainActor.run{
NSApp.dockTile.badgeLabel = ""
}
}
}
#endif
// register notification(macOS/iOS)
extension AppDelegate {
func registerForPushNotifications() {
UNUserNotificationCenter.current()
.requestAuthorization(options: [.alert, .sound, .badge]) {
(granted, error) in
print("Permission granted: \(granted)")
}
}
}
@main
struct SimplePushNotificationApp: App {
#if os(iOS)
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
#endif
#if os(macOS)
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
#endif
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
var body: some View {
Text("Push notification testbed")
.padding()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment