How to get device token in iOS 13 with Xamarin?

2020-02-12 09:02发布

问题:

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?

回答1:

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.



回答2:

You can use a more simplified version:

var bytes = deviceToken.ToArray();
var token = BitConverter.ToString(bytes).Replace("-", "");


回答3:

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



回答4:

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?



回答5:

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..