Home > Software design >  SwiftUI ask notification permission on start without button
SwiftUI ask notification permission on start without button

Time:12-19

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.

CodePudding user response:

This is easy:

import SwiftUI
import UserNotifications


@main
struct RSApp: App {
    let center = UNUserNotificationCenter.current()
    
    init() {
        registerForNotification()
    }
    
    func registerForNotification() {
        //For device token and push notifications.
        UIApplication.shared.registerForRemoteNotifications()
        
        let center : UNUserNotificationCenter = UNUserNotificationCenter.current()
        //        center.delegate = self
        
        center.requestAuthorization(options: [.sound , .alert , .badge ], completionHandler: { (granted, error) in
            if ((error != nil)) { UIApplication.shared.registerForRemoteNotifications() }
            else {
                
            }
        })
    }
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

CodePudding user response:

In your case you are modifying App root View. So you can put your code into either init or onAppear. 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 in onAppear modifier is called only when the view is shown. So your code can look like this:

import SwiftUI


@main
struct RSApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
            .onAppear() {
                let center = UNUserNotificationCenter.current()
                center.requestAuthorization(options: [.alert, .sound, .badge]) { success, error in
                    if let error = error {
                        // Handle the error here.
                    }
                    // Enable or disable features based on the authorization.
                }
            }
        }
    }
}
  • Related