SwiftUI 在第二个视图中提示通知权限

SwiftUI prompt notification permission in second view

我的项目中有 2 个视图,即登录视图和主页视图。我尝试在用户登录成功后在home视图提示通知权限。尝试后,我找到了Push Notification for Beginner。应用程序首次在登录视图中启动时的权限提示。有没有办法设置权限协议的视图?

struct ContentView: View {
    @EnvironmentObject var authService:AuthService

    var body: some View{
        ZStack{
            if(!authService.signedIn){
                RegisterView()
            }
            else{
                HomePageView() //The view I want to ask for permission after signedIn
            }
        }
    }
}
import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        let auth = UserDefaults.standard.object(forKey: "Auth")
        //if auth != nil {
        //    registerForPushNotifications()
        //}  //what I tried, but It prompt while user restart the app after login.
        registerForPushNotifications()
        return true
    }

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }

    func registerForPushNotifications() {
      //1
      UNUserNotificationCenter.current()
        //2
        .requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] granted, _ in
            print("Permission granted: \(granted)")
            guard granted else { return }
            self?.getNotificationSettings()
          }

    }
    func getNotificationSettings() {
      UNUserNotificationCenter.current().getNotificationSettings { settings in
        print("Notification settings: \(settings)")
        guard settings.authorizationStatus == .authorized else { return }
        DispatchQueue.main.async {
          UIApplication.shared.registerForRemoteNotifications()
        }

      }
    }
    func application(
      _ application: UIApplication,
      didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
    ) {
      let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
      let token = tokenParts.joined()
      print("Device Token: \(token)")
    }
}

实际上,当用户启动应用程序时(在 application(_:, didFinishLaunchingWithOptions:) 内),您实际上是在请求通知访问权限。您必须在成功登录后调用 registerForPushNotifications 方法。

例如:

        // successful login
        // e.g: authService..signedIn = true
        (UIApplication.shared.delegate as? AppDelegate).registerForPushNotifications()