Iphone 设备令牌 - NSData 或 NSString
我正在接收 NSData
对象形式的 iPhone 设备令牌。 当我测试通知脚本功能时,我只从日志中复制了该对象,并且通知运行良好。但是,当我现在尝试自动执行此操作时,我以变量的形式将设备令牌作为 ASCII 编码字符串发送。
self.deviceToken = [[NSString alloc] initWithData:webDeviceToken encoding:NSASCIIStringEncoding];
我得到的字符串有一些时髦的字符,看起来类似于此“å-0⁄fZÿ÷ʺÎUQüRáqEªfÔk« "
当服务器端脚本向该令牌发送通知时,我没有收到任何内容。
我需要解码某些东西以及如何解码?
问候
I am receiving iPhone device token in the form of NSData
object.
When I tested my notifications script function, I have only copied that object from log and the notifications went fine. However when I try now to automatically do it, I am sending the device token as ASCII encoded string in the form of variable
self.deviceToken = [[NSString alloc] initWithData:webDeviceToken encoding:NSASCIIStringEncoding];
The string that I am getting has some funky characters and looks similar to this "å-0¾fZÿ÷ʺÎUQüRáqEªfÔk«"
When server side script sends the notification to that token, I am not receiving anything.
Do I need to decode something and how?
Regardz
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
好的,我找到了解决方案。如果有人遇到同样的问题,请忘记 ASCII 编码,只需使用以下几行创建字符串:
Ok, I found a solution. If anyone has the same problem, forget about ASCII encoding, just make the string with the following lines:
如果有人正在寻找在 Swift 中执行此操作的方法:
编辑:对于 Swift 3,
Swift 3 引入了带有值语义的
Data
类型。要将deviceToken
转换为字符串,您可以执行以下操作:If anyone is looking for a way to do this in Swift:
Edit: For Swift 3
Swift 3 introduces the
Data
type, with value semantics. To convert thedeviceToken
to a String, you can do as follows:我发现这个解决方案更好,因为 iOS 可以在未来版本中更改描述的使用,因此在数据上使用描述属性将来可能不可靠。
我们可以通过从数据令牌字节创建十六进制令牌来直接使用它。
我们
还可以将设备令牌存储在 NSUserdefaults 中,并在稍后使用它将其发送到我们的服务器。
I found this solution better as iOS can change the usage of description in future versions, so using description property on data can be unreliable in future.
We can directly use this by creating hex Token from the data token bytes.
}
We can also store the device token in our NSUserdefaults and use it later to send it out to our server.
我认为这不是一个好的解决方案,因为您必须在将通知发送到 Apple 服务器之前重建字符串。使用 Base64 编码来传输字符串或类似的内容。
I don't think it's a good solution, as you have to reconstruct the string before sending the notifications to Apple servers. Use Base64 encoding for transmitting the strings or something similar.
将设备令牌转换为十六进制字符串的另一种方法
Another way of converting device token into hexa decimal string
对于 Swift 3 :
其他方法
创建用于获取十六进制字符串的数据扩展
并在中调用此扩展
For Swift 3 :
Other Method
Create Data extension for getting hexstring
And call this extension in