Created
July 2, 2024 18:46
-
-
Save lienmt/72a726e4ca43a1eba625b49b386ff4d1 to your computer and use it in GitHub Desktop.
NotificationManager in SwiftUI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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