Search code examples
iosswiftfirebasegoogle-cloud-firestoreuiimage

Firebase Firestore iOS: How can I save images to a collection in the firestore?


So I have an app where users can add annotations to the map, and I want these created annotations to be visible and accessible to EVERY user. I am trying to write annotation data to Firestore, but it seems as images are not supported. I also tried converting the images to base64EncodedString's, but then the document exceeds the size limit of 1mb by a LOT. (Usually 10 mb or so). Here's my code:

let strBase64UserPickedImage =  image?.pngData()?.base64EncodedString()
let strBase64DefaultImage = UIImage(named: "Image-1")?.pngData()?.base64EncodedString()

// User gave both 'warnings' and 'image' values
    if warnings != nil && image != nil {
        db.collection("jumpSpotAnnotations").addDocument(data: [

            "title": title,
            "coordinate": coords,
            "estimatedHeight": estimatedHeight,
            "locationDescription": locationDescription,
            "warnings": warnings!,
            "image": strBase64UserPickedImage!

        ]) { (error) in
            if let e = error {
                print("There was an issue saving data to firestore: \(e)")
            } else {
                print("Successfully saved data.")
            }
        }
    }

There are more parts to that 'if' statement, but they are irrelevant. How can I save an image without exceeding the size limit? If it is literally impossible to save images with Firestore, is there another way with firebase? Remember, I'm trying to make it so that these annotations are accessible to every user no matter who it was created by, I'm not trying to make a userDefault or anything. Thanks for any help!


Solution

  • In general, Firestore is not suitable for large binary data like images. The preferred approach is to use Cloud Storage for Firebase to store the binary data, and use Firestore to store a path to that image in the storage bucket where you've uploaded it.