繁体   English   中英

应用程序:didRegisterForRemoteNotificationsWithDeviceToken:未称为ios 10.3.2

[英]application:didRegisterForRemoteNotificationsWithDeviceToken: not called ios 10.3.2

我想开发一个使用推送通知的简单代码。 我根据现有的教程(例如linkthis)创建证书和配置文件,但是注册函数application:didRegisterForRemoteNotificationsWithDeviceToken:根本没有被调用,因此我无法获得设备令牌。

我还在xcode的“功能”选项卡中为背景打开了“推送通知”和“远程通知”。 这是我在AppDelegate.swift代码

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


    UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
    UIApplication.shared.registerForRemoteNotifications()

    return true
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    print("APNs device token: \(deviceTokenString)")
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("APNs registration failed: \(error)")
}

func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
    print("Push notification received: \(data)")
}

在此处输入图片说明

我正在使用运行iOS 10.3.2的iPhone 5s

请从didFinishLaunchingWithOptions方法调用registerForNotifications

 //MARK:- Methods
    func registerForNotifications(){
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.delegate = self
            center.requestAuthorization(options:[.alert,.sound]) { (granted, error) in
                if granted{
                    UIApplication.shared.registerForRemoteNotifications()
                }else{
                    print("Notification permission denied.")

                }
            }

        } else {
            // For ios 9 and below
            let type: UIUserNotificationType = [.alert,.sound];
            let setting = UIUserNotificationSettings(types: type, categories: nil);
            UIApplication.shared.registerUserNotificationSettings(setting);
            UIApplication.shared.registerForRemoteNotifications()
        }
    }


func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = String(format: "%@", deviceToken as CVarArg).trimmingCharacters(in: CharacterSet(charactersIn: "<>")).replacingOccurrences(of: " ", with: "")
        print(token)

    }

我找不到它为什么没有被调用的原因,但是当我将测试目标更改为运行iOS 10.3.2的iPhone 7时,它运行良好。

我不确定为什么会这样,但是更改目标可能会解决问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM