How to convert NSString to String in MonoTouch

I am trying to implement push notifications for MonoTouch, but I could not find samples of this anywhere. My problem is trying to read the deviceID in the .NET string.

The result below is just a lot of question marks, so I'm doing something wrong here.

Any help would be greatly appreciated!

public override void RegisteredForRemoteNotifications (UIApplication application, NSData deviceToken) { Console.WriteLine("Converting device ID..."); NSString s = NSString.FromData(deviceToken, NSStringEncoding.UTF8); Console.WriteLine("DEVICE ID IS: " + s); s = NSString.FromData(deviceToken, NSStringEncoding.ASCIIStringEncoding); Console.WriteLine("DEVICE ID IS: " + s); s = NSString.FromData(deviceToken, NSStringEncoding.Unicode); Console.WriteLine("DEVICE ID IS: " + s); } 
+4
source share
3 answers

Here is a great article showing how to make push notifications using MonoTouch:

http://weblogs.thinktecture.com/cweyer/2010/12/implementing-push-notifications-for-ios-with-c-monotouch-using-the-cloud-urban-airship.html

Here is a snippet that does what you want:

 var str = (NSString)Runtime.GetNSObject ( Messaging.intptr_objc_msgSend (deviceToken.Handle, new Selector("description").Handle)); var deviceTokenString = str.ToString ().Replace ("<", "").Replace (">", "").Replace (" ", ""); 
+2
source

MonoTouch has an operator for implicit conversion.

So you just do:

 NSString s = NSString.FromData(deviceToken, NSStringEncoding.UTF8); string csstring = s; // done 

Alternatively, you can use the NSString ToString() method:

 NSString s = NSString.FromData(deviceToken, NSStringEncoding.UTF8); string csstring = s.ToString(); 

Below is the documentation .

+6
source

I managed to implement this and I used the following code:

 NSString newDeviceToken = new NSString(MonoTouch.ObjCRuntime.Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr(new MonoTouch.ObjCRuntime.Class("NSString").Handle, new MonoTouch.ObjCRuntime.Selector("stringWithFormat:").Handle, strFormat.Handle, deviceToken.Handle)); string token = newDeviceToken.ToString(); 

This will provide you with a string that reads

 < 64characterlonghexstring > 

You can use Regex to get rid of spaces, and "<" ">" as required.

I found that the following project is very useful for receiving a monochrome push notification implementation: C # Apple Push Notification Service - it provides client-side code as well as server-side code.

0
source

All Articles