在 Firebase 中使用图像填充表格视图

Populating Tableviews with Images in Firebase

我最近问了这个问题:Populating a UITableView in Firebase a Set Number of Cells at a time

但是通过讨论我发现这个问题实际上是两个问题,所以我要为第二个问题开第二个话题:

人们通常使用 Firebase 从大型数据集中填充图像的表格视图有什么方法吗?

下面是我用来检索图像的代码。图像是 base64 编码的 NSString。

NSString* profPicString= [child.value objectForKey: @"profilePicture"];
    NSData *dataFromBase64=[NSData base64DataFromString:profPicString];
    UIImage *profPicImage = [[UIImage alloc]initWithData:dataFromBase64];
    item.profilePicture = profPicImage;

但是,这些图像需要很长时间才能下载。仅包含 10 张图像的表格视图将需要 5 或 10 秒来加载。 10张图片就这样,成百上千张就真的是冰川了。

我怀疑我是第一个遇到这个问题的人,我想知道是否有 better/more 有效的方法来解决这个问题?

感谢您的帮助!

如果您要将图像存储为 base64 编码字符串,请将它们存储在 Firebase 数据库中的单独位置。

{
   "pokemon": {
      "001": {
         "name": "Bulbasaur"
      },
      "002": {
         "name": "IvySaur"
      }
   },
   "images": {
      "001": "big-ole-base64-string",
      "002": "big-ole-base64-string"
   }
}

这样你就可以加载主要数据而不需要下载图像。

现在,当您为 UITableView 加载数据时,为主要数据集创建侦听器,在本例中为 /pokemon

然后当你到达 tableView(_:cellForRowAtIndexPath) 时,创建一个一次性侦听器来抓取图像。

这个例子在Swift,但是你可以转换成Objective-C。

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCellWithIdentifier("PokeCell") as! PokeTableViewCell

  let pokeSnap = pokemonSnaps[indexPath.item]

  let imageRef = rootRef.childByAppendingPath("images").childByAppendingPath(pokeSnap.key)

  imageRef.observeSingleEventOfType(.Value) { (imageSnap: FDataSnapshot!) in
    let base64String = imageSnap.value as! String
    let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0))
    let image = UIImage(data: decodedData!)
    cell.pokeImage.image = image
  }

  return cell   
}

这种方法的优点在于您只在需要时加载图像,而不是主要数据集。

Check out this repo of mine that implements this technique.

推荐的新方法是使用 Firebase Storage,Firebase 的新文件和图像存储解决方案。您可以将它与 SDWebImage 等东西结合使用,以显示您上传到 Firebase 存储的图像。

我们很快就会用这些信息更新所有 samples/repos:)