从Firestore加载图像并将其保存到Swift

时间:2018-06-15 18:54:05

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

我正在处理一个必须在每次启动时从服务器加载一些图像和数据的应用程序(以确保它使用最新信息)。我将Firestore用作数据库,并且当前将图像存储为Firebase存储的URL。

以某种方式可以在Firestore中存储实际图像吗?我怎样才能缓存加载的图像?来自

UIImage(contentsOf: URL)

还是来自Firestore?

4 个答案:

答案 0 :(得分:1)

尝试使用具有缓存支持的异步图像下载器作为UIImageView类别 - http://cocoadocs.org/docsets/SDWebImage 它被称为sdwebimage真的很容易使用

答案 1 :(得分:0)

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

将实际文件数据存储在云存储中(使用客户端上的Firebase SDK),然后将引用或URL存储到文档中,然后仅在需要时从那里获取它将会好得多。 / p>

答案 2 :(得分:0)

您可以使用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")

答案 3 :(得分:0)

I don't know if that's the most efficient way of solving my problem but I did it the following way:

In my Firestore DB I stored references to images in Cloud Storage. Then when app starts for the first time, it loads those files from Firestore DB using default methods AND saves those images in app's container (Documents folder) using Swift's FileManager().

Next time the app starts, it goes through references array and skips the files which are already in app's container.