我目前在我的php文件中使用JSON从我的数据库中检索信息,我们称之为getJson.php:
<?php
include ("config.php");
$query = "SELECT id,title,text,image,date FROM posts";
$result = mysql_query($query) or die(mysql_error());
$num = mysql_num_rows($result);
$rows = array();
while ($r = mysql_fetch_assoc($result)){
$rows[] = $r;
}
echo json_encode($rows);
?>
然后在我的应用程序中,我使用:
检索JSON表示NSURL *url = [NSURL URLWithString:kGETUrlPosts];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
postsArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
我还将二进制图像数据存储为BLOB,我想要检索。但是我不能JSON使用JSON编码这个二进制数据,可以吗?
我的第二个选择是在图像字段中保留我的图像的URL,然后调用
UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"www.myURL.com/MyPhotos/somephoto.png"]]];
答案 0 :(得分:0)
我们的解决方案 3 步骤。
<强>步骤1。创建一个专用的PHP脚本,接受$ _GET参数'imageId'
<?php
//Lets call this script as 'getImage.php'.
//This script should be publicly accessible
//Example format: http://www.yourdomain.com/getImage.php?imageId=2
include ("config.php");
$query = "SELECT image FROM posts WHERE id=" . mysql_real_escape_string($_GET['imageId']);
$result = mysql_query($query) or die(mysql_error());
$r = mysql_fetch_assoc($result);
//display the image
$im = imagecreatefromstring($r['image']);
if ($im !== false) {
// I assume you use only jpg
//You may have to modify this block if you use some othe image format
//visit: http://php.net/manual/en/function.imagejpeg.php
header('Content-Type: image/jpeg');
imagejpeg($im);
imagedestroy($im);
} else {
echo 'error.';
}
?>
<强>第二步。修改你的getJson.php
<?php
include ("config.php");
//Notice the change in query.
$query = "SELECT id,title,text,date FROM posts";
$result = mysql_query($query) or die(mysql_error());
$num = mysql_num_rows($result);
$rows = array();
while ($r = mysql_fetch_assoc($result)){
//Please replace below url with your real server url.
$r['image'] = 'http://www.yourdomain.com/getImage.php?imageId=' . $r['id'];
$rows[] = $r;
}
echo json_encode($rows);
?>
Step3 - IOS结束 - 显示图像
图片网址存在于你的repsponse数组中(我认为是postsArray)。您只需像处理普通图像一样处理每行中的图像网址!
注意: