首页 > 解决方案 > APNS 推送通知 iOS 13 - didRegisterForRemoteNotificationsWithDeviceToken 未被调用

问题描述

我发现一些帖子已经在堆栈溢出,但它们已经过时并且不再实际了。

我在实现推送通知时遇到问题。

Xcode 11、iOS 13、App 刚刚创建,因此证书适用于 Xcode 11 或更高版本,启用了推送通知和背景模式(处理、远程通知、获取)。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        //Firebase Messaging

        registerForPushNotifications()

        UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate
        Messaging.messaging().delegate = self as MessagingDelegate

//        //Locationtracking
//
//        guard let isLocationEnabled = UserDefaults.standard.value(forKey: "userEnabledLocationTracking") as? Bool else {locationManager.stopLocationTracking(); return true}
//
//        isLocationEnabled ? locationManager.startLocationTracking() : locationManager.stopLocationTracking()

        return true
    }

之后我调用这两个函数:

func registerForPushNotifications() {
        UNUserNotificationCenter.current()
            .requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] granted, error 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 {
                    print("register called.......")
                    UIApplication.shared.registerForRemoteNotifications()
                }
        }
    }

但是我的“didRegisterForRemoteNotificationsWithDeviceToken” - 委托方法没有被调用,我不明白为什么会发生这种情况。

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Auth.auth().setAPNSToken(deviceToken, type: .unknown)
        Messaging.messaging().apnsToken = deviceToken

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

如果有人可以帮助我并告诉我我的错误在哪里,那就太好了。

祝你今天过得愉快!

标签: iosswiftpush-notification

解决方案


推荐阅读