首页 > 解决方案 > iOS Xcode 12.4 SwiftUI 应用程序中的推送通知:didRegisterForRemoteNotificationsWithDeviceToken -> 永远不会被调用

问题描述

我一直在寻找这个。我正在使用一个没有经典 AppDelegate 的纯 swiftUI 应用程序。

我一直在创建一个手动 appDelegate 来安装 Firebase,它长期以来一直像魅力一样工作。我最近添加了通知支持,但我遇到了问题。通知批准过程工作得很好,我已经能够在模拟器上发送通知,但是当我尝试在真实设备上发送推送通知时,我需要 tokenID 和 didRegisterForRemoteNotificationsWithDeviceToken 似乎永远不会被调用,即使我得到了我成功的打印确认挂号的。

请帮忙。一直在尝试很多 Wifi 开/关等。在没有专门的 AppDelegate 部分的纯 SwiftUI 应用程序中实现这一点似乎很困难。

import SwiftUI
import Firebase
import UserNotifications

@main
struct KidBooksApp: App {
    
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            let viewModel = AppViewModel()
            withAnimation(.easeInOut(duration: transitionTime())) {
                //TextComposeView()
                //ImageChooserView()
                ContentView()
                    .transition(.fly)
                    //.transition(.fly)
                    .environmentObject(viewModel)
            }
        }
    }
    
    
}

class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        registerForPushNotifications()
        FirebaseApp.configure()
        
        return true
    }
    
    func application(_ application: UIApplication,
                didRegisterForRemoteNotificationsWithDeviceToken
                    deviceToken: Data) {
        print("test success")
        let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
        let token = tokenParts.joined()
        print("Device Token: \(token)")
    }
    
    func application(
      _ application: UIApplication,
      didFailToRegisterForRemoteNotificationsWithError error: Error
    ) {
      print("test error")
      print("Failed to register: \(error)")
    }
    
    func registerForPushNotifications() {
        UNUserNotificationCenter.current()
          .requestAuthorization(
            options: [.alert, .sound, .badge]) { [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()
            print("Registered: \(UIApplication.shared.isRegisteredForRemoteNotifications)")
        }

      }
    }
    
    

}

/* 调试控制台打印:

授予的权限:true 通知设置:<UNNotificationSettings: 0x16de61780; authorizationStatus:已授权,notificationCenterSetting:已启用,soundSetting:已启用,badgeSetting:已启用,lockScreenSetting:已启用,carPlaySetting:不支持,announcementSetting:不支持,criticalAlertSetting:不支持,alertSetting:已启用,alertStyle:横幅,groupingSetting:默认提供AppNotificationSettings:否>已注册:true

*/

标签: swiftuipush-notificationappdelegatexcode12

解决方案


推荐阅读