首页 > 解决方案 > SwiftUI 应用程序生命周期中的远程推送通知不起作用

问题描述

将出现通知权限请求,然后我将按允许和所有这些,但没有任何委托功能(didFailToRegisterForRemoteNotificationsWithError 或 didRegisterForRemoteNotificationsWithDeviceToken 工作,我正在真实设备上测试......)。我已在 Signing & Capabilities 中启用推送通知,并已通过 Apple Developer 注册证书并将其保存到我的钥匙串中。任何帮助,将不胜感激!

@main
struct Sparrow_NavigationApp: App {
    
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            RootView {
                ContentView()
            }
        }
    }
}

class AppDelegate: NSObject, UIApplicationDelegate {
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        UNUserNotificationCenter.current()
          .requestAuthorization(
            options: [.alert, .sound, .badge]) { granted, _ in
            print("Permission granted: \(granted)")
            guard granted else { return }
            UNUserNotificationCenter.current().getNotificationSettings { settings in
                print("Notification settings: \(settings)")
                guard settings.authorizationStatus == .authorized else { return }
                DispatchQueue.main.async {
                  application.registerForRemoteNotifications()
                }
              }
          }
        return true
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        guard let aps = userInfo["aps"] as? [String: AnyObject] else {
            completionHandler(.failed)
            return
          }
        print("got something, aka the \(aps)")
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("device token")
        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("Device Token not found.")
    }
}

https://i.stack.imgur.com/MkfDh.png

https://i.stack.imgur.com/dABWZ.png

标签: iosswiftxcodeswiftuiapple-push-notifications

解决方案


推荐阅读