I would like to request notification permission from the user on startup without forcing the user to click a specific button.
Xcode 14.2
My application structure:
import SwiftUI
import UserNotifications
@main
struct RSApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
Now where should I add this code to request permission?
center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if let error = error {
// Handle the error here.
}
// Enable or disable features based on the authorization.
}
(from https://developer.apple.com/documentation/usernotifications/asking_permission_to_use_notifications)
I know I can add it as a function call to the button, but I would like to request access without the user having to click anything, so basically when the view is initialized.
2
Answers
This is easy:
In your case you are modifying App root View. So you can put your code into either
init
oronAppear
. I’d suggest to use latter (onAppear
) just to follow best practices. SwiftUI creates all the views immediately, even destination views for navigation links, which means that initializers are run immediately. While code placed inonAppear
modifier is called only when the view is shown. So your code can look like this: