【问题标题】:Load image from Firestore and save it to cache in Swift从 Firestore 加载图像并将其保存到 Swift 中的缓存
【发布时间】:2018-06-15 18:54:04
【问题描述】:

我正在开发一个应用程序,该应用程序必须在每次启动时从服务器加载一些图像和数据(以确保它使用的是最新信息)。我将 Firestore 用作数据库,目前将图像作为指向 Firebase 存储的 URL 存储在其中。

是否可以在 Firestore 中存储实际图像?以及如何缓存加载的图像?来自

UIImage(contentsOf: URL)

还是来自 Firestore?

【问题讨论】:

    标签: ios swift xcode firebase google-cloud-firestore


    【解决方案1】:

    试试这个带有缓存支持的异步图像下载器作为 UIImageView 类别 - http://cocoadocs.org/docsets/SDWebImage 叫sdwebimage真的好用啊

    【讨论】:

      【解决方案2】:

      您可以在 Firestore 中使用 bytes 类型(请参阅 list of types)来保存您想要的任何二进制数据(在 iOS 上使用 NSData),但这几乎肯定不是您真正想要做的。整个文档的大小限制为 1 MB,图像很容易超过该大小。此外,您将在任何时候阅读该文档时支付将该图像下载到客户端的费用,这可能是一种浪费。

      您最好将实际文件数据存储在 Cloud Storage 中(使用客户端上的 Firebase SDK),然后将引用或 URL 存储在文档中,并仅在需要时从那里获取。

      【讨论】:

      • 您提到 iOS 上的 NSData 将数据存储为 Firestore 中的“字节”类型。您是否知道如何将数据存储为 web api 中的“字节”类型?
      • 对于其他阅读,我在这里找到了答案:stackoverflow.com/a/53672081/2441655
      【解决方案3】:

      你可以使用https://github.com/pinterest/PINRemoteImage,这个框架使用https://github.com/pinterest/PINCache

      import PINRemoteImage
      
      extension UIImageView {
      
          public func setImageFrom(urlString: String!, animated: Bool = false) {
      
      
              guard let urlString = urlString else {
                  return
              }
      
      
              guard let url = URL(string: urlString) else {
                  return
              }
      
              layer.removeAllAnimations()
              pin_cancelImageDownload()
              image = nil
      
              if !animated {
                  pin_setImage(from: url)
              } else {
                  pin_setImage(from: url, completion: { [weak self] result in
                      guard let _self = self else { return }
                      _self.alpha = 0
                      UIView.transition(with: _self, duration: 0.5, options: [], animations: { () -> Void in
                          _self.image = result.image
                          _self.alpha = 1
                      }, completion: nil)
                  })
              }
          }
      }
      

      ....

      UIImageView(). setImageFrom(urlString: "https://ssssss")
      

      【讨论】:

        【解决方案4】:

        我不知道这是否是解决我的问题的最有效方法,但我是通过以下方式做到的:

        在我的 Firestore 数据库中,我将图像的引用存储在 Cloud Storage 中。然后,当应用程序第一次启动时,它会使用默认方法从 Firestore DB 加载这些文件,并使用 Swift 的 FileManager() 将这些图像保存在应用程序的容器(文档文件夹)中。

        下次应用启动时,它会遍历引用数组并跳过已经在应用容器中的文件。

        【讨论】:

          猜你喜欢
          • 2020-05-25
          • 1970-01-01
          • 2016-05-16
          • 1970-01-01
          • 1970-01-01
          • 2021-03-14
          • 1970-01-01
          • 1970-01-01
          • 2019-09-21
          相关资源
          最近更新 更多