Search code examples
c#iosxamarin.iosin-app-purchasestorekit

Convert NSData to base64encoded AND a byte array in C#


I'm implementing in-app purchasing for our iOS app for various auto-renewable subscriptions. When the payment is complete we need to send the transaction information to our server (cloud) to record the information so that we can verify the receipt on a set interval to make sure the subscription is valid, not cancelled/refunded, or renewed. We are going to make the JSON calls from the server on a set interval to do this via the in-app purchasing guide and our shared secret, have yet to get to that but before we do we need to have the relevant data from the purchase, i.e. the TransactionReceipt which is an NSData object.

We want to send two parameters to our web service for the TransactionReceipt (among other items such as the ProductID purchased, etc.). We want to send this as a base64encoded value which is what we believe needs to be sent in the JSON request for validation, so we'll store that in SQL Server.

HOw, using MonoTouch / C# can we convert the NSData "TransactionReceipt" to base64encoded and also a byte[]?

Thank you.


Solution

  • There's two easy way to get data out of NSData, using a Stream or the Bytes and Length properties. The stream version would look like:

    public byte[] ToByte (NSData data)
    {
        MemoryStream ms = new MemoryStream ();
        data.AsStream ().CopyTo (ms);
        return ms.ToArray ();
    }
    

    the Bytes and Length version would be:

    public byte[] ToByte (NSData data)
    {
        byte[] result = new byte[data.Length];
        Marshal.Copy (data.Bytes, result, 0, (int) data.Length);
        return result;
    }
    

    Getting the base64 output string remains identical:

    public string ToBase64String (NSData data)
    {
        return Convert.ToBase64String (ToByte (data));
    }