Skip to content

Instantly share code, notes, and snippets.

@lienmt
Created July 2, 2024 18:46
Show Gist options
  • Save lienmt/72a726e4ca43a1eba625b49b386ff4d1 to your computer and use it in GitHub Desktop.
Save lienmt/72a726e4ca43a1eba625b49b386ff4d1 to your computer and use it in GitHub Desktop.
NotificationManager in SwiftUI
import Foundation
import UserNotifications
import SwiftUI
@MainActor
class NotificationManager: ObservableObject{
@Published private(set) var hasPermission = false
init() {
Task{
await getAuthStatus()
}
}
func request() async{
do {
try await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound])
await getAuthStatus()
} catch{
print(error)
}
}
func getAuthStatus() async {
let status = await UNUserNotificationCenter.current().notificationSettings()
switch status.authorizationStatus {
case .authorized, .ephemeral, .provisional:
hasPermission = true
default:
hasPermission = false
}
}
}
@main
struct YourApp: App {
@StateObject
private var notificationManager = NotificationManager()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(notificationManager)
}
}
}
struct ContentView: View {
@EnvironmentObject
private var notificationManager: NotificationManager
var body: some View {
Text("Hello Indie App Accelerator!")
.onAppear {
if !notificationManager.hasPermission {
Task {
await notificationManager.request()
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment