【问题标题】:How to get image from json response and display in collection view ios如何从json响应中获取图像并在集合视图ios中显示
【发布时间】:2015-08-26 04:35:36
【问题描述】:

我是 iOS 新手,我从 json 获取图像 url。现在我想在集合视图上显示它。我正在做下面的代码。但无法在集合视图中显示图像。有人可以帮我解决这个问题吗?enter code here

// 集合查看代码

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{

    return imageArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    if(!cell)
    {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
        UIImageView *myImageView = [[UIImageView alloc]initWithFrame:CGRectMake(50,0, 50, 80)];
        myImageView.tag = 101;
        [cell.contentView addSubview:myImageView];
    }


    NSString *myImage = [imageArray objectAtIndex:indexPath.row];

    NSString *ImageString = [myImage stringByReplacingOccurrencesOfString:@"" withString:@"%20"];

    NSLog(@"Image String %@",ImageString);

    NSURL *imageURL = [NSURL URLWithString:ImageString];

    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];

    UIImageView *img = (UIImageView*)[cell.contentView viewWithTag:101];
    img.backgroundColor = [UIColor redColor ];

    cell.backgroundView = [UIImage imageWithData:imageData];

    return cell;

}

// Json 服务

NSDictionary *get = @{@"uid":[uidSave valueForKey:@"uid"],@"pro":proNumber};
        NSLog(@"Dictionary Data which is to be get %@",get);

        NSData* jsonData = [NSJSONSerialization dataWithJSONObject:get options:kNilOptions error:nil];
        NSString *jsonInputString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSString *post = [[NSString alloc]initWithFormat:@"r=%@",jsonInputString];

        NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"%@",displayCaseUrl]];

        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
        NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120.0];
        [request setURL:url];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postData];

        NSError *error;
        NSURLResponse *response;
        NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
        if (responseData != nil)
        {
            jsonDict = (NSMutableDictionary *)[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
            NSLog(@"Values =======%@",jsonDict);

            NSMutableDictionary *imageDict = [jsonDict valueForKey:@"images"];
            NSLog(@"Image Dictionary :- %@",imageDict);
            imageArray = [imageDict valueForKey:@"image_url"];
            NSLog(@"MY Array Image :- %@",imageArray);

// 要获取图像的 Json 响应

Image Dictionary :- (
        {
        "image_url" = "http://zapponomics.net/claimservice/parcelimage/1486154806image0.jpg";
        "img_for" = "Front view of parcel";
        "pro_number" = orange;
    }
)
2015-08-26 10:09:05.806 ClaimCloud[1997:87342] MY Array String :- (
    "http://zapponomics.net/claimservice/parcelimage/1486154806image0.jpg"
)

//////// USIng 像这样但是不行

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    UIImageView *myImageView = [[UIImageView alloc]initWithFrame:CGRectMake(50,0, 50, 80)];
    myImageView.tag = 101;
    [cell.contentView addSubview:myImageView];
    NSString *myImage = [imageArray objectAtIndex:indexPath.row];
   [self loadImageFromURL:[NSURL URLWithString:[myImage stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] callback:^(UIImage *image) {
        myImageView.image = image;
    }];
    return cell;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0,200);

}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(100,80);

}
- (void) loadImageFromURL: (NSURL*) url callback:(void (^)(UIImage *image))callback {
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^{
        NSData * imageData = [NSData dataWithContentsOfURL:url];
        dispatch_async(dispatch_get_main_queue(), ^{
            UIImage *image = [UIImage imageWithData:imageData];
            callback(image);
        });
    });
}

【问题讨论】:

    标签: ios arrays json


    【解决方案1】:

    有一个非常好的库,名为SDWebImage,它可以帮助您从 URL 加载图像。如上述@poojathorat 的回答,如果图像尺寸较大,您将图像转换为数据,而不是你会遇到内存问题,但是这个库也会管理内存。所以我认为使用这个库。

    只需拖动项目中的 SDWebImage 文件夹并导入

    #import "UIImageView+WebCache.h"
    

    然后使用此方法从 URL 加载图像

    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    

    它还将管理图像的缓存。

    如果您不想包含库,请使用此功能

    - (void) loadImageFromURL: (NSURL*) url callback:(void (^)(UIImage *image))callback {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
        dispatch_async(queue, ^{
            NSData * imageData = [NSData dataWithContentsOfURL:url];
            dispatch_async(dispatch_get_main_queue(), ^{
                UIImage *image = [UIImage imageWithData:imageData];
                callback(image);
            });
        });
    }
    

    并像这样使用这个函数

    [self loadImageFromURL:[NSURL URLWithString:["yourURL" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] callback:^(UIImage *image) {
        yourImageView.image = image;
    }]
    

    【讨论】:

    • 你能告诉我不添加任何库吗?/?
    • 添加库有什么问题,也会异步加载图片。
    • 我不想包含任何库.. 你能告诉我不添加库吗
    • 我已经编辑了答案,以防你的 URL 中有空格。
    • 无法在收藏视图中显示图片
    【解决方案2】:

    不用%20替换空格,按照以下方式直接申请。

    NSString *myImage = [imageArray objectAtIndex:indexPath.row];
    NSURL *url = [NSURL URLWithString:myImage];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *image = [UIImage imageWithData:data];
    cell. myImageView.image = [UIImage imageNamed:img];
    

    【讨论】:

    • @##poojathorat UIImage *img = [[UIImage alloc] initWithData:data cache:NO];并且错误是ui图片缓存没有可见界面
    • 现在找不到 imageview 的属性 .. 在最后一行单元格上显示错误。 myImageView.image = [UIImage imageNamed:img];
    • UIImageView *myImageView 在上面声明这个 if(!cell) 条件
    • 你已经在 if 条件下声明了它,所以这个属性没有得到
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-10
    相关资源
    最近更新 更多