将图像保存到Cloud Firestore

时间:2019-05-02 20:14:43

标签: swift firebase google-cloud-firestore

将图像上传到Firebase存储后,如何将图像保存到Firebase Firestore?

将图像上传到Firebase存储后,如何将图像保存到Firebase Firestore?

我应该有带有标题和图片的帖子,但是我不知道该怎么做图片部分。

我的代码如下所示。

import Foundation
import FirebaseFirestore


protocol DocumentSerializable {
    init?(dictionary:[String:Any])
}


struct Post {
    var name: String
    var content: String
    var downloadURL: String

    var dictionary: [String:Any] {

        return [
            "name": name,
            "content": content,
            "imageDownloadURL": downloadURL
        ]
    }

}

extension Post: DocumentSerializable {
    init?(dictionary: [String : Any]) {
        guard let name = dictionary["name"] as? String,
        let content = dictionary["content"] as? String,
            let downloadURL = dictionary["imageDownloadURL"] as? String else {return nil}

        self.init(name: name, content: content, downloadURL: downloadURL)

    }



}




import UIKit
import Firebase
import FirebaseStorage

class PostCell: UICollectionViewCell {

    @IBOutlet weak var thumbnailImageView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!

    var post: Post! {
        didSet {
            self.updateUI()
        }
    }

    func updateUI() {

        // download image
        if let imageDownloadURL = post?.downloadURL {
            let imageStorageRef = Storage.storage().reference(forURL: imageDownloadURL)
            imageStorageRef.getData(maxSize: 2 * 1024 * 1024) { [weak self] (data, error) in
                if let error = error {
                    print("******** \(error)")
                } else {
                    if let imageData = data {
                        let image = UIImage(data: imageData)
                        DispatchQueue.main.async {
                            self?.thumbnailImageView.image = image
                        }
                    }
                }

            }
        }
    }


}

1 个答案:

答案 0 :(得分:1)

您没有将图片保存到Firestore中,而是保存了图片网址。将图片保存到存储中后,您必须获取该图片的网址,然后将其保存到firestore中。只需谷歌这些步骤或查看文档以获取更多信息