php - 使用 PHP 和 jSON 从 MySQL 获取 UIImage

标签 php iphone mysql objective-c json

我正在开发一个小型新闻阅读器,它通过对 URL 执行 POST 请求来从网站检索信息。响应是一个带有未读新闻的 jSON 对象。

例如App 上的最新消息的时间戳为“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}]

然后应用程序获取响应并解析它,获得一个 NSDictionary 并将其添加到核心数据数据库中。

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

我的问题是:如何将图像添加到 MySQL 数据库、存储它、使用 jSON 通过 POST HTTP 请求传递它,然后将其解释为 UIImage。

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

最佳答案

虽然您可以对图像进行 base64 编码并将其粘贴到输出 json 中...

当我处于您的情况时,我所做的是在 json 输出中包含指向该图像的 url 链接,然后获取数据:

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

这样做可以让您在上传、存储和下载时将图像简单地视为普通图像。

关于php - 使用 PHP 和 jSON 从 MySQL 获取 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17373870/

相关文章:

PHP SSL 证书指纹

html - Safari 视口(viewport)错误,固定位置和底部或顶部的问题

iphone - 在 UIBarButtonItem setTintColor 上发送的无法识别的选择器

iphone - 触摸并在屏幕上拖动图像

mysql - 无法让 mysql gem 在 Snow Leopard 中工作,无法在 rails 环境中设置 ruby

mysql - 奇怪的MySQL用聚合函数连接查询结果

php - 在 laravel postgres 中搜索多维 jsonb 数据

php - 输入正确的 Google Recaptcha 挑战和激活码后无法重定向到所需页面

php - 使用自动对焦打开模态弹出窗口

php - 需要帮助将脚本从 PDO 转换为 Mysql