【问题标题】:How to extract image from JSON response in iOS如何从 iOS 中的 JSON 响应中提取图像
【发布时间】:2013-12-24 11:08:15
【问题描述】:

我正在从 webService 解析 JSON,它为我提供图像、文本等。文本可以被提取,但我如何从中获取图像?

这就是 JSON 响应的样子。

[
 {  "photo": "23_841676772.jpg",
    "date": "2013-06-06 08:11:15",
    "tags": "",
    "ID_article": "1",
    "commentcount": "5"
 },
]

我试图在 tableView:cellForRow 方法中这样设置它不起作用。

    NSMutableDictionary *tempDict3 = [self.jsonArray objectAtIndex:indexPath.row];
    cell.blogImageView.image = [UIImage imageNamed:[tempDict3 objectForKey:@"photo"]];

【问题讨论】:

  • 您是否从 JSON(照片密钥)获取 url?如果是这样,那么你做错了..
  • 你的资源中有23_841676772.jpg吗?
  • 是的 23_841676772.jpg 位于哪里 .. ?你得到的只是图像名称+扩展名..
  • 将“服务器上图片的网址”作为 photo 的值,然后从该路径下载后台图片。
  • 好的..任何示例代码家伙?....

标签: ios json web-services parsing


【解决方案1】:

我使用了静态 json,你可以用你的 json url 替换 str。

NSString *Str =[NSString stringWithFormat:@"[{\"photo\": \"23_841676772.jpg\",\"date\":\"2013-06-06 08:11:15\",\"tags\": \"\",\"ID_article\": \"1\",\"commentcount\": \"5\"},{\"photo\": \"dfdgfdgd.jpg\",\"date\":\"2013-06-06 08:11:15\",\"tags\": \"\",\"ID_article\": \"1\",\"commentcount\": \"5\"}]"];


NSDictionary *catgDict = [NSJSONSerialization JSONObjectWithData:[Str dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];

for(NSDictionary *dict in catgDict)
{
    NSLog(@"dd: %@",dict);
    NSLog(@"Photo: %@",[dict valueForKey:@"photo"]);
}

【讨论】:

    【解决方案2】:

    请您的网络服务团队在您的回复中添加另一个标记为“image_url”,以便您可以将图像 url 转换为图像。如果他们说出于安全原因我们不能提供它,那么剩下的唯一选择就是硬编码路径并将“图像名称”附加到它上面,这样您就可以获得完整的图像 url,现在您可以将其转换为图像。

    【讨论】:

    • 好的,谢谢你的建议:-]
    • 欢迎哥们度过愉快的一天
    【解决方案3】:

    要从 JASON 响应中提取照片名称,您可以使用此代码

    JSONResponse : [
     {  "photo": "23_841676772.jpg",
        "date": "2013-06-06 08:11:15",
        "tags": "",
        "ID_article": "1",
        "commentcount": "5"
     },
    ]
    

    .h 文件中创建一个数组对象

    @interface ViewController : UIViewController
    {
        NSMutableArray * photoNameData;
    }
    

    .m 文件中

    photoNameData =[[NSMutableArray alloc] init];
    NSMutableArray * tmpAry = JSONResponse;
    if (tmpAry.count !=0) {
            for (int i=0; i<tmpAry.count; i++) {
                NSMutableDictionary * tmpDictn = [tmpAry objectAtIndex:i];
                [photoNameData addObject:[tmpDictn objectForKey:@"photo"]];
            }
        }
    


    您可以使用以下代码下载文档目录中的图片。

    for (int i=0; i<photoNameData.count; i++) {  //updated here
    
    //First check that document directory contain image or not  
            NSString* tmpStr = [photoNameData objectAtIndex:i];  // used the photoNameData to get image name
            NSString* tmpImgURL = [NSString stringWithFormat:@"%@%@",@"http://www.my server.com/web_services/photos/",tmpStr];   //merge the image name and url
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documents = [paths objectAtIndex:0];
            NSString* foofile = [documents stringByAppendingPathComponent:tmpStr];
            BOOL imageExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];
    
    //  if image not exist than download it
                if (!imageExists) {
                            NSLog(@"%@ not exist",tmpImgURL);
                            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:tmpImgURL] cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:10.0];
                            [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *err){
                                if (!err && data) {
                                    //NSLog(@"data : %@",data);
                                    NSString *finalPath = [documents stringByAppendingPathComponent:tmpStr];
                                    NSLog(@"finalPath : %@",finalPath);
                                    [data writeToFile:finalPath atomically:YES];
                                }else{
                                    NSLog(@"err : %@",err);
                                }
                            }];
                        }
    }
    

    您可以使用此代码使用此图像..

    NSString* tmpStr = [photoNameData objectAtIndex:indexPath.row];  //get the image name from photoNameData
    NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    UIImage * image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",documentsDirectoryPath, tmpStr]];
    cell.blogImageView.image = image;
    

    【讨论】:

    • 嗯,你的答案的第一部分没有提供图片。我想我需要下载图片......
    • 只有当您的应用程序包中有图像时,答案的第一部分才有效。但是如果您从服务器获取图像,那么答案的第二部分会有所帮助。但请记住,您需要的图片 URL 不仅仅是它的名称。
    • http://my server/web_services/photos/...这是我服务器上的照片文件夹...包含所有图片...
    • 你的tmpImgURL 将是my server/web_services/photos/23_841676772.jpg
    • tmpImgURL 检查更新。你的 URL 看起来像这样。
    猜你喜欢
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多