如何用从URL(iOS)下载的图片填充表格?

时间:2016-03-21 11:04:22

标签: ios json image uitableview alamofire

我有一个UITableView填充JSON,通过Alamofire,在JSON中,我需要为每个单元格下载图像的网址。我的问题是,一旦我下载了图像,当他抛出图表时,图像会被重新下载,并且单元格会有错误的图像,直到完成下载正确的图像。如何将下载的图像保存在适当的单元格中? 这是我的代码:

override func viewDidLoad() {
    super.viewDidLoad()
    self.refreshTable()

}
func refreshTable(){
    Alamofire.request(.GET, urlComponent, parameters: nil, encoding:.JSON).responseJSON
        { response in switch response.result {
        case .Success(let JSON):

            let data = JSON as! Dictionary<String, AnyObject>
            for (_,value) in data{
                let object = value as! NSMutableArray
                for item in object{
                    self.arrayData.addObject(item)
                }
            }
            self.tableView.reloadData()
        case .Failure(let error):
            print("Request failed with error: \(error)")
            }
    }

}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if(self.arrayData.count != 0){
        return self.arrayData.count

    }
    else{
        return 0

    }
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CollectionCell
            if(self.arrayData.count != 0){
   let dizionario = self.arrayData.objectAtIndex(indexPath.row) as! NSDictionary
        cell.titolo.text = dizionario.objectForKey("title") as? String
        cell.code.text = dizionario.objectForKey("code") as? String

            let url = NSURL(string:dizionario.objectForKey("img") as! String)!

            Alamofire.request(.GET, url, parameters: nil).responseData
                { response in switch response.result {
                case .Success(let JSON):
                    let data = JSON
                    cell.immagine.image = UIImage(data: data)

                case .Failure(let error):
                    print("Request failed with error: \(error)")

                    }
            }

    }

    return cell


}

3 个答案:

答案 0 :(得分:0)

你应该为此创建一个自定义单元格...你可以在这个方法中覆盖名为prepareForReuse的单元格方法...在这个方法中初始化你的cell.imageview.image = nil;这样你的imageview.image将是零,直到从服务器下载的图像

func prepareForReuse()
{
    cell.imageView.image = nil;
}

答案 1 :(得分:0)

这不可能,因为当一个细胞离开视野时。当它被重新创建时,它会再次被破坏。您可以使用SDWebImage这是一个库,这将帮助您在机器的内存中一次性存储图像,您不需要在重新加载单元格时一次又一次地发出网络请求。

答案 2 :(得分:0)

以这种方式思考:1-on viewDidLoad 当你到达需要下载我们有2个选项的图像点时,你打电话给 yourUrl 就是检查一下图像缓存在磁盘上或否则如果是,则从磁盘获取它,如果没有则将其下载并缓存到磁盘

这里是我使用的方法:

UIActivityIndicatorView *view  = [(UIActivityIndicatorView *)cell viewWithTag:500];
[view setColor:[UIColor colorWithRed:255/255.0 green:198/255.0 blue:39/255.0 alpha:1.0f]];
[view startAnimating];

menuItem *event  = [self.listOfMenuItem objectAtIndex:index];
NSString *cachedKey  = event.menuItemUrlImage;



SDImageCache *imageCache = [[SDImageCache alloc] initWithNamespace:@"yourSDImageCache"];

[imageCache queryDiskCacheForKey:cachedKey done:^(UIImage *image, SDImageCacheType cacheType)               {

if (image) {


    UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];

    recipeImageView.layer.cornerRadius = recipeImageView.frame.size.width/2;

    recipeImageView.layer.borderColor = [UIColor colorWithRed:31/255.0 green:97/255.0 blue:51/255.0 alpha:1.0f].CGColor;

    CGSize h = CGSizeMake(180, 180);
    recipeImageView.image = [self imageWithImage:image scaledToSize:h :cell];

    [view stopAnimating];






}else{

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{


        NSURL *url  = [NSURL URLWithString:event.menuItemUrlImage];


        [[SDWebImageDownloader sharedDownloader]downloadImageWithURL:url options:SDWebImageDownloaderLowPriority progress:^(NSInteger receivedSize, NSInteger expectedSize) {

        } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {




            if (finished && image){
                [view stopAnimating];
                UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];

                recipeImageView.layer.cornerRadius = recipeImageView.frame.size.width/2;

                recipeImageView.layer.borderColor = [UIColor colorWithRed:31/255.0 green:97/255.0 blue:51/255.0 alpha:1.0f].CGColor;

                CGSize h = CGSizeMake(180, 180);
                recipeImageView.image = [self imageWithImage:image scaledToSize:h :cell];


                [imageCache setMaxCacheAge:60*60*24];

                [imageCache storeImage:image
                  recalculateFromImage:NO
                             imageData:data
                                forKey:event.menuItemUrlImage
                                toDisk:YES];
            }
        }];





    });
}
}];

SDWebImage希望得到这个帮助