在 Swift 4 中获取远程通知设备令牌? [英] Getting Remote Notification Device Token in Swift 4?

查看:22
本文介绍了在 Swift 4 中获取远程通知设备令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码获取通知中心设备令牌.

I am using this code to get the Notification Center Device token.

它适用于 Swift 3,但不适用于 Swift 4.发生了什么变化?

It was working in Swift 3 but not working in Swift 4. What changed?

if #available(iOS 10.0, *) {
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in

    }
}

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

推荐答案

假设你已经检查了一切都设置正确,根据你的代码,它似乎应该可以正常工作,你所要做的就是改变格式为 %02.2hhx 而不是 %02X 以获得适当的十六进制字符串.因此你应该得到一个有效的.

Assuming that you already checked that everything has been setup right, based on your code, it seems that it should works fine, all you have to do is to change the format to %02.2hhx instead of %02X to get the appropriate hex string. Thus you should get a valid one.

作为一种好的做法,您可以在项目中添加一个 Data 扩展以获取字符串:

As a good practice, you could add a Data extension into your project for getting the string:

import Foundation

extension Data {
    var hexString: String {
        let hexString = map { String(format: "%02.2hhx", $0) }.joined()
        return hexString
    }
}

用法:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let deviceTokenString = deviceToken.hexString
    print(deviceTokenString)
}

这篇关于在 Swift 4 中获取远程通知设备令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆