DidRegisterForRemoteNotificationsWithDeviceToken никогда не вызывался

Мне нужна помощь.

Я понятия не имею, почему мои уведомления не работают.

Мой AppDelegate выглядит так:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        print("token: \(token)")
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("failed to register for remote notifications with with error: \(error)")
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
    
        UNUserNotificationCenter.current().delegate = self
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
            print("granted: (\(granted)")
        }
    
        UIApplication.shared.registerForRemoteNotifications()
    
        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.
    }
}

Проблема в том, что функция didRegisterForRemoteNotificationsWithDeviceToken никогда не вызывается. Я также создал SSL-сертификаты службы push-уведомлений Apple в своей учетной записи разработчика, добавил Push-уведомления к своим возможностям в Xcode, но он все еще не работает. Каждый раз, когда я нажимаю «Разрешить», чтобы разрешить уведомления, он говорит, что доступ предоставлен, но не распечатывает токен устройства. isRegisterForRemoteNotifications также возвращает true.

Я также искал в Интернете около 2-3 часов, но пока не смог найти никакого решения.

Я использую Xcode 12 Beta 2 и iOS 14 Dev Beta 2.

Спасибо.


person Pinnokkio    schedule 10.07.2020    source источник


Ответы (1)


Вам нужно запустить свой код на реальном устройстве, вы не можете получить токен на симуляторе

person Marshall    schedule 10.07.2020
comment
Я сделал. Я установил приложение на свой настоящий iPhone, но оно по-прежнему не работает. Если я выхожу из приложения в переключателе приложений, иногда появляется сообщение, что push-уведомления недоступны на симуляторах, но это настоящее устройство ... - person Pinnokkio; 11.07.2020
comment
У тебя такая строка token: что ли? - person Marshall; 11.07.2020
comment
Нет, ничего. Это похоже на то, что метод никогда не вызывается. - person Pinnokkio; 11.07.2020
comment
Можете ли вы попробовать изменить подключение Wi-Fi на 4g и снова открыть приложение? - person Marshall; 11.07.2020
comment
Да, это сработало. Но только в 4G. Какой в ​​этом смысл? - person Pinnokkio; 11.07.2020
comment
@pinnokkio, я не знаю, но проблема присутствует в ios 13 и до сих пор не решена - person Marshall; 11.07.2020
comment
Очень интересно, откуда ты знаешь? - person Pinnokkio; 11.07.2020
comment
Реши это? У меня такая же проблема в iOS 14 Beta 4. - person xyzlast; 15.08.2020
comment
@xyzlast Можете ли вы попробовать изменить подключение Wi-Fi на 4g и снова открыть приложение? - person Marshall; 19.08.2020
comment
У меня такая же проблема. Когда я бегал на своем реальном устройстве, это работало. Маршал, я был подключен к Wi-Fi. - person Caio Santos; 21.09.2020