iphonensstringnsdata

Convert NSData [UIImage] to a NSString


I am aware this question has been asked several times, but I was unable to find a definite answer that would best fit my situation.

I want the ability to have the user select an image from the library, and then that image is converted to an NSData type. I then have a requirement to call a .NET C# webservice via a HTTP get so ideally I need the resulting string to be UTF8 encoded.

This is what I have so far:

NSData *dataObj = UIImageJPEGRepresentation(selectedImage, 1.0);
    [picker dismissModalViewControllerAnimated:YES];
    NSString *content =  [[NSString alloc] initWithData:dataObj encoding:NSUTF8StringEncoding];
    NSLog(@"%@", content);

The NSLog statement simply produces output as:

2009-11-29 14:13:33.937 TestUpload2[5735:207] (null)

Obviously this isn't what I hoped to achieve.


Solution

  • You can't create a UTF-8 encoded string out of just any arbitrary binary data - the data needs to actually be UTF-8 encoded, and the data for your JPEG image obviously is not. Your binary data doesn't represent a string, so you can't directly create a string from it - -[NSString initWithData:encoding:] fails appropriately in your case.

    Assuming you're using NSURLConnection (although a similar statement should be true for other methods), you'll construct your NSMutableURLRequest and use -setHTTPBody: which you need to pass an NSData object to. I don't understand why you would be using a GET method here since it sounds like you're going to be uploading this image data to your web service - you should be using POST.