Say that I have the Python code:
someString = file("filename.jpg").read()
How can I replicate this line of code in Objective C on iOS? I’m trying to convert a jpg into a string, for eventual url encoding so I can pass it on to the Tumblr API. I tried base64 encoding to convert the image to a string initially, but that doesn’t seem to get a valid response from tumblr. I also tried NSUTF8Encoding, but those attempts return nil strings (see below).
Why am I doing this? Someone from Tumblr posted a Python example of how to submit multiple photos for a photoset in response to this thread, and the process appears to start with converting the images to strings using file.read(). The API unfortunately doesn’t take a simple ‘multipart/form-data’ request, only ‘application/x-www-form-urlencoded’ format.
What sort of encoding is Python using to do this read(), and how can I replicate it in Objective C on the iPhone?
I have tried the following:
NSString *utf8String = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"filename" ofType:@"jpg"] encoding:NSUTF8StringEncoding error:&error];
This gives a nil string and error 261 The operation couldn’t be completed.
Using base64 encoding gives me a string, but the Tumblr API doesn’t accept it after url encoding it, so I assume it’s not doing what Python is doing with read() (though I could just be missing a step). The Tubmlr API responds with "status":400,"msg":"Bad Request"},"response":{"errors":["Error uploading photo."]
There is a similar question on stackoverflow about uploading photos to photosets on Tumblr here, but this question is more specific to the posted Python code.
I figured the answer out by simply logging the string — it looks like it’s a hexadecimal format, with \xXX where XX is the hexadecimal code for each byte, with ASCII substitutions for certain easily-printed characters.
The above can be replicated in Objective C by reading in the image to NSData, and then getting the description (which is a list of 2 digit hexadecimal-formatted byte values). After that, you could loop through each byte and decide how to represent it based on its value: