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

查看:183
本文介绍了在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.

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

As a good practice, you could add 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天全站免登陆