2013-06-28 50 views
3

我正在开发一个小新闻阅读器,通过对URL进行POST请求从网站检索信息。响应是带有未读消息的jSON对象。使用PHP和jSON从MySQL获取UIImage

E.g.该应用程序的最新消息有一个“2013-03-01”的时间戳。当用户刷新表格时,它会显示“domain.com/api/api.php?newer-than=2013-03-01”。 api.php脚本进入MySQL数据库并获取2013-03-01之后发布的所有新闻,并打印出json_encoded。这是

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

例如响应将是[{"title": "new app is coming to the market", "text": "lorem ipsum dolor sit amet...", image: XXX}]

在App然后得到的响应,并且将其解析,获得NSDictionary,并将其添加到核心数据DB。

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

我的问题是:如何将图像添加到MySQL数据库,使用JSON海槽POST HTTP请求存储,通过它,然后把它解释为一个UIImage的。

很明显,要将UIImage存储在CoreData中,它们必须转换成/从NSData转换。我如何使用php和jSON将NSData来回传递给MySQL数据库?我应该如何将图像上传到数据库? (系列化,为BLOB,等等)

回答

2

虽然你可以Base64编码,您的图片,并坚持认为到您的输出JSON ...

我所做的,当我在你的情况是,包括URL链接该图像而不是在JSON输出,然后获取数据:

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]; 

这样做,这样可以让你上传时,存储和下载它只是简单地将图像作为正常图像。