Reputation: 145
How do I save the image to the firebase firestore, when I have uploaded the image to the firebase storage?
I am supposed to have posts with a title and an image, but I don't know how to do the image part.
my code is shown below ....
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
}
}
}
}
}
}
}
Upvotes: 5
Views: 8121
Reputation:
You don’t save image into firestore but image url. After you save image into storage you have to get the url of that image and then save the url to firestore. Just google these steps or see documentation for more info
Upvotes: 5