user10230043
user10230043

Reputation:

How to save multiple images to firebase?

Currently I have an app where hen the user takes a picture it automatically gets saved in storage and then I save an url to the image in storage. But whenever I add new images it just changes the old one to the new one. I want to append new ones. The end goal is for a user to be able to save an array of images he took to firebase under his account.

Bellow is my code for saving the images a user takes:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        if let userPickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {

//            let imageToUse = PhotoArray()

//            let data = UIImagePNGRepresentation(userPickedImage) //here convert to data

            PhotoArray.sharedInstance.photosArray.append(userPickedImage)  //append converted data in array

            //                do {
            //                    try realm.write {
            //                        realm.add(imageToUse)
            //                    }
            //                } catch {
            //                    print(“error adding image to array\(error)“)
            //                }

            imageView.image = userPickedImage
//-----------------------------//
            //Create a reference to the image
            let imageRef = Storage.storage().reference().child("image.jpg")

            // Get image data
            if let uploadData = UIImagePNGRepresentation(userPickedImage) {

                // Upload image to Firebase Cloud Storage
                imageRef.putData(uploadData, metadata: nil) { (metadata, error) in
                    guard error == nil else {
                        // Handle error
                        return
                    }
                    // Get full image url
                    imageRef.downloadURL { (url, error) in
                        guard let downloadURL = url else {
                            // Handle error
                            return
                        }

                        // Save url to database
                        Firestore.firestore().collection("images").document("myImage").setData(["imageUrl" : downloadURL.absoluteString])
                    }
                }
            }
//-----------------------------//
        }
//        print(PhotoArray().photosArray.count)
        imagePicker.dismiss(animated: true, completion: nil)
    }

Upvotes: 0

Views: 953

Answers (2)

AlrightyRob
AlrightyRob

Reputation: 163

Here is a little snippet of how I got multiple images to save with Firebase storage. I called uploadProfileImage() twice and set the NSUUID().uuidString inside the Storage path so basically on each instance the function is called, the time of the call would be a barely different and not overwrite :)

@IBAction func saveImages(_ sender: Any) {

    self.uploadProfileImage(frontImage!) { url in

        if url != nil {
            print("success")

        } else {
            print("failed!")
        }

    }
    self.uploadProfileImage(backImage!) { url in

        if url != nil {
            print("success")

        } else {
            print("failed!")
        }

    }


    dismiss(animated: false, completion: nil)
}

func uploadProfileImage(_ image:UIImage, completion: @escaping ((_ url:URL?)->())) {
    guard let uid = Auth.auth().currentUser?.uid else { return }
    let imageTime = NSUUID().uuidString
    let storageRef = Storage.storage().reference().child("users/\(uid)/\(imageTime)")

    let imageData = image.jpegData(compressionQuality: 0.75)

    let metaData = StorageMetadata()
    metaData.contentType = "image/jpg"

    storageRef.putData(imageData!, metadata: metaData) { metaData, error in
        if error == nil, metaData != nil {

            storageRef.downloadURL{ url, error in
                completion(url)
            }

        }
        else {
            completion(nil)
        }
    }
}

Upvotes: 1

Everett Flynn
Everett Flynn

Reputation: 111

You can't save images to Firebase Cloud Firestore. You could try using Firebase Cloud Storage, by going to Google and searching for the Firebase Cloud Storage docs.

Upvotes: 0

Related Questions