axlrtr
axlrtr

Reputation: 575

How to get device token in iOS 13 with Xamarin?

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?

Upvotes: 11

Views: 5841

Answers (7)

Naphstor
Naphstor

Reputation: 2496

There is a field in deviceToken object called DebugDescription. Format that field and you will get the token.

var myToken = deviceToken.DebugDescription.Replace("<", string.Empty).Replace(">", string.Empty).Replace(" ", string.Empty).ToUpper();

Upvotes: 0

Pedro Silva
Pedro Silva

Reputation: 19

Convert NSData to String

 var tokenStringBase64 =deviceToken.GetBase64EncodedString(NSDataBase64EncodingOptions.None);

Convert String to NSData

var deviceToken = new NSData(tokenStringBase64, NSDataBase64DecodingOptions.None);

Upvotes: 1

ypakala
ypakala

Reputation: 1209

You can use a more simplified version:

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

Upvotes: 4

Steve Schofield
Steve Schofield

Reputation: 119

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

Upvotes: -1

Kevin Le - Khnle
Kevin Le - Khnle

Reputation: 10857

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

Upvotes: 6

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?

Upvotes: -1

axlrtr
axlrtr

Reputation: 575

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.

Upvotes: 28

Related Questions