Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a NSString to a String in MonoTouch

Tags:

xamarin.ios

I am trying to implement push notifications for MonoTouch but I couldn´t find samples of this anywhere. My problem is trying to read the deviceID into a .NET string.

The output below is just a lot of question marks so I am 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);


    }
like image 985
Christer Nordvik Avatar asked Dec 12 '10 11:12

Christer Nordvik


2 Answers

There is an operator for implicit conversion in MonoTouch.

So you just do:

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

Alternatively, you can use NSString's ToString() method:

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

Here's related documentation.

like image 163
Pablo Santa Cruz Avatar answered Oct 05 '22 14:10

Pablo Santa Cruz


Here's a great article showing how to do push notifications with MonoTouch:

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

Here's the 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 (" ", "");
like image 23
Nikolai Sander Avatar answered Oct 05 '22 12:10

Nikolai Sander