Xamarin.iOS iOS13 获取DeviceToken
随着苹果iOS13系统的发布,DeviceToken的获取方式发生了一定的变化。
iOS13之前获取DeviceToken方法
public override void RegisteredForRemoteNotifications (
UIApplication application, NSData deviceToken)
{
// Get current device token
var DeviceToken = deviceToken.Description;
if (!string.IsNullOrWhiteSpace(DeviceToken)) {
DeviceToken = DeviceToken.Trim('<').Trim('>');
}
}
这段代码运行在 iOS 13 上已经无法获取到准确的DeviceToken字符串了,iOS 13 通过deviceToken.Description获取到的内容已经变了。
{length = 32, bytes = 0x14b54623 58494431 974ecc27 f44b1fdb ... 1dc9bc64 9d334520 }
iOS13之后获取DeviceToken方法
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
byte[] dataBytes = new byte[deviceToken.Length];
System.Runtime.InteropServices.Marshal.Copy(deviceToken.Bytes, dataBytes, 0, Convert.ToInt32(deviceToken.Length));
StringBuilder builder = new StringBuilder();
foreach (var b in dataBytes)
{
builder.AppendFormat("{0:X2}", b);
}
DeviceToken = builder.ToString();
}
经过以上处理后:
3FCF3268B7FCEF9C550F92D84632525F623B5A6C8BB3349B1F3845BB95B41992
如此即可正常获取DeviceToken啦。