NSData for NSString using initWithBytes: length: encoding

I have some image data (jpeg) that I want to send from my iPhone application to my web service. To do this, I use NSData from the image and convert it to a string that will be placed in my JSON.

I am currently doing this:

NSString *secondString = [[NSString alloc] initWithBytes:[result bytes] length:[result length] encoding:NSUTF8StringEncoding]; 

Where is the result of type NSData. However, secondString seems to be null, although the length of the result returns a real value (for example, 14189). I used this method because the result is raw data, not zero completion.

Am I doing something wrong? I used this code in other areas, and it seems to work fine (but the areas in which I am currently using it include data that does not contain images).

TIA.

+4
source share
2 answers

For binary data, it is better to encode it using Base64 encoding and then decode it in your web service. I am using the NSData + Base64 class, downloaded from here , this link was also taken from Stackoverflow's answer, made by @Ken (Thanks Ken!).

+2
source

You do not convert data to a string. You are trying to interpret it as a UTF-8 encoded string, which will fail if the data is really not a UTF-8 encoded string. It is best to encode it, possibly with Base64, as Manny suggests, and then decode it again on the server.

+2
source

All Articles