How to get device token in iOS 13 with Xamarin?

2020-02-12 08:38发布

Our RegisteredForRemoteNotifications code broke because the token was retrieved with:

deviceToken.ToString().Trim('<').Trim('>').Replace(" ", "");

This used to work but not with iOS 13 because the data will be like this:

"{length = 32, bytes = 0x965b251c 6cb1926d e3cb366f dfb16ddd ... 5f857679 376eab7c }"

There's answers for how to do this correctly with objective c and swift but I haven't found one with C#.

Reference:

Get device token for push notification

https://nshipster.com/apns-device-tokens/

How to do this with Xamarin?

5条回答
家丑人穷心不美
2楼-- · 2020-02-12 09:08

Here's another way to do:

var bytes = deviceToken.ToArray<byte>();
var hexStringArray = bytes.Select(b => b.ToString("x2")).ToArray();    
var token = string.Join(string.Empty, hexStringArray);

The code above is based on a post by NSHipster as I described in my own post https://medium.com/@kevinle/correctly-capture-ios-13-device-token-in-xamarin-3d0fa390b71b

查看更多
够拽才男人
3楼-- · 2020-02-12 09:08

I´m having the same problem and was trying to implement based on this post: https://onesignal.com/blog/ios-13-introduces-4-breaking-changes-to-notifications/

I´m going to test your solution the first chance I get but have you tested to see if it maintains compatibility with previous iOS builds?

查看更多
三岁会撩人
4楼-- · 2020-02-12 09:28

Looks like I found the answer myself:

byte[] result = new byte[deviceToken.Length];
Marshal.Copy(deviceToken.Bytes, result, 0, (int) deviceToken.Length);
var token = BitConverter.ToString(result).Replace("-", "");

Using this code I was able to get a device token and send a notification.

查看更多
对你真心纯属浪费
5楼-- · 2020-02-12 09:30

This worked for me on iOS 13. The linq option has better perf I'd think. Have to test iOS 12 to see if it's backwards compat. Worked on iOS 12 as well. This fixed my issue! Thanks for sharing with a code newb..

查看更多
家丑人穷心不美
6楼-- · 2020-02-12 09:34

You can use a more simplified version:

var bytes = deviceToken.ToArray();
var token = BitConverter.ToString(bytes).Replace("-", "");
查看更多
登录 后发表回答