【问题标题】:Getting a UIImage from MySQL using PHP and jSON使用 PHP 和 JSON 从 MySQL 获取 UIImage
【发布时间】:2013-06-28 21:21:00
【问题描述】:

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

例如应用程序上的最新消息的时间戳为“2013-03-01”。当用户刷新表格时,它会发布“domain.com/api/api.php?newer-than=2013-03-01”。 api.php 脚本进入 MySQL 数据库并获取 2013 年 3 月 1 日之后发布的所有新闻并以 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 并将其添加到Core Data db。

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

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

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

【问题讨论】:

    标签: php iphone mysql objective-c json


    【解决方案1】:

    虽然您可以对图像进行 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];
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-07
      • 2016-09-22
      • 2014-12-25
      • 2011-06-16
      • 2016-11-04
      • 1970-01-01
      • 2018-07-07
      • 1970-01-01
      相关资源
      最近更新 更多