Daniel
Daniel

Reputation: 1341

Getting a UIImage from MySQL using PHP and jSON

I'm developing a little news reader that retrieves the info from a website by doing a POST request to a URL. The response is a jSON object with the unread-news.

E.g. the last news on the App has a timeStamp of "2013-03-01". When the user refreshes the table, it POSTS "domain.com/api/api.php?newer-than=2013-03-01". The api.php script goes to the MySQL database and fetches all the news posted after 2013-03-01 and prints them json_encoded. This is

// do something to get the data in an array
echo $array_of_fetched_data;

for example the response would be [{"title": "new app is coming to the market", "text": "lorem ipsum dolor sit amet...", image: XXX}]

the App then gets the response and parses it, obtaining an NSDictionary and adds it to a Core Data db.

 NSDictionary* obtainedNews = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

My question is: How can I add an image to the MySQL database, store it, pass it using jSON trough a POST HTTP Request and then interpret it as an UIImage.

It's clear that to store an UIImage in CoreData, they must be transform into/from NSData. How can I pass the NSData back and forth to a MySQL db using php and jSON? How should I upload the image to the db? (Serialized, as a BLOB, etc)

Upvotes: 3

Views: 550

Answers (1)

CodeReaper
CodeReaper

Reputation: 6145

While you could base64 encode your images and stick that into your output json...

What I did when I was in your situation was to include a url link to that image instead in the json output and then fetching the data:

NSString *image = @"http://dphi.ca/files/2010/01/flower.png";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:image] options:NSDataReadingUncached error:&error];
// write the data down somewhere as to not fetch it all the time
UIImage *uimage = [UIImage imageWithData:data];

Doing it this way will allow you to simply treat the image as a normal image when uploading, storing and downloading it.

Upvotes: 2

Related Questions