Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading Multiple Images simultaneously with Google Firebase

I'm using Google Firebase in a Swift iOS project. I have a part of my app where the user selects more than 1 photo from their device to upload. I'm trying to find the best practice for uploading all the photos they selected at once to Firebase Storage. I know how to upload one photo.

I looked through the Docs and didn't see any methods about uploading multiple NSData objects, so would I just run a for loop and upload each image individually?

Thanks! All feedback is appreciated.

like image 753
justColbs Avatar asked Dec 07 '22 22:12

justColbs


1 Answers

Swift 3 This is how I am uploading multiple images to Firebase. I am making a count of successful uploads, if its equal to the number of images supplied, thats when I am calling a completion handler.

Not sure if this is the best practice, but it works!!

import Foundation
import Firebase
import FirebaseDatabase
import FirebaseStorage

class UploadImages: NSObject{

static func saveImages(imagesArray : [UiImage]){

        Auth.auth().signInAnonymously() { (user, error) in
            //let isAnonymous = user!.isAnonymous  // true
            //let uid = user!.uid
            if error != nil{
                print(error)
                return
            }
            guard let uid = user?.uid else{
                return
            }

            uploadImages(userId: uid,imagesArray : imagesArray){ (uploadedImageUrlsArray) in
                print("uploadedImageUrlsArray: \(uploadedImageUrlsArray)")
            }
        }
    }


static func uploadImages(userId: String, imagesArray : [UIImage], completionHandler: @escaping ([String]) -> ()){
    var storage     =   Storage.storage()

    var uploadedImageUrlsArray = [String]()
    var uploadCount = 0
    let imagesCount = imagesArray.count

    for image in imagesArray{

        let imageName = NSUUID().uuidString // Unique string to reference image

        //Create storage reference for image
        let storageRef = storage.reference().child("\(userId)").child("\(imageName).png")


        guard let myImage = image else{
            return
        }
        guard let uplodaData = UIImagePNGRepresentation(myImage) else{
            return
        }

        // Upload image to firebase
        let uploadTask = storageRef.putData(uplodaData, metadata: nil, completion: { (metadata, error) in
            if error != nil{
                print(error)
                return
            }
            if let imageUrl = metadata?.downloadURL()?.absoluteString{
                print(imageUrl)
                uploadedImageUrlsArray.append(imageUrl)

                uploadCount += 1
                print("Number of images successfully uploaded: \(uploadCount)")
                if uploadCount == imagesCount{
                    NSLog("All Images are uploaded successfully, uploadedImageUrlsArray: \(uploadedImageUrlsArray)")
                    completionHandler(uploadedImageUrlsArray)
                }
            }

        })


        observeUploadTaskFailureCases(uploadTask : uploadTask)   
    }  
} 


//Func to observe error cases while uploading image files, Ref: https://firebase.google.com/docs/storage/ios/upload-files


    static func observeUploadTaskFailureCases(uploadTask : StorageUploadTask){
        uploadTask.observe(.failure) { snapshot in
          if let error = snapshot.error as? NSError {
            switch (StorageErrorCode(rawValue: error.code)!) {
            case .objectNotFound:
              NSLog("File doesn't exist")
              break
            case .unauthorized:
              NSLog("User doesn't have permission to access file")
              break
            case .cancelled:
              NSLog("User canceled the upload")
              break

            case .unknown:
              NSLog("Unknown error occurred, inspect the server response")
              break
            default:
              NSLog("A separate error occurred, This is a good place to retry the upload.")
              break
            }
          }
        }
    }

}

Usage

let arrayOfImages : [UIImage] = [Image1, Image2, Image3]
UploadImages.saveImages(imagesArray: arrayOfImages)
like image 61
SpaceX Avatar answered Mar 03 '23 08:03

SpaceX