Hamza
Hamza

Reputation: 151

Send Form Data in Firestore using Swift

i'm using Firestore in my app, i have a form in which there is an image,name and array containing name and image. Now i want it to send it to Firestore DB. I'm trying like this,

func saveTeamAPI()
{
    let image = teamImage.image
    let data = image!.jpegData(compressionQuality: 1.0)

    // set upload path
    let db = Firestore.firestore()
    var ref: DocumentReference? = nil
    ref = db.collection("Team").addDocument(data: [
        "teamName": teamNameTxt.text!,
        "teamImage": data!,
        "players": playerArray
    ]) { err in
        if let err = err {
            print("Error adding document: \(err)")
        } else {
            print("Document added with ID: \(ref!.documentID)")
        }
    }
}

I'm confused about one thing how can I send an image in Firestore and an array of names and images?

How can i resolve this?

Upvotes: 0

Views: 378

Answers (1)

Zafar Ivaev
Zafar Ivaev

Reputation: 133

I suggest you to use Firebase Storage, as it is an efficient way to store images. Here is how you do it: 1) Loop through an array of images and upload them one by one to storage. 2) After each successful upload, get image url and append it to array called imagesURLs.

let storage = Storage.storage()
let storageRef = storage.reference()

var imagesURLs = [String]()

for image in images.enumerated() {

let newImageRef = storageRef.child(/\(image.0)avatar.jpg")

let data = image.jpegData(compressionQuality: 0.0)

_ = newImageRef.putData(data!, metadata: nil) { (metadata, error) in

            guard metadata != nil else {
                print(error as Any)
                return
            }

            newImageRef.downloadURL(completion: { (url, error) in
                guard url != nil else {
                    return
                }

                print("Avatar uploaded: \(url!.absoluteString)")

                imagesURLs.append(url!.absoluteString)
            })
        }
}

After you get all urls, you can use Firestore to send them as "imageURLs": imageURLs

Upvotes: 3

Related Questions