Uploading Multiple Images simultaneously with Google Firebase

后端 未结 2 1183
长情又很酷
长情又很酷 2020-12-14 13:34

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

相关标签:
2条回答
  • 2020-12-14 14:08

    Answered by @FrankVanPuffellen in comments...

    "You'd indeed just loop and upload them individually. Your iOS user might also appreciate if you upload them one at a time, so that they can abort the upload midways through without losing progress on all images." – Frank van Puffelen

    0 讨论(0)
  • 2020-12-14 14:14

    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)
    
    0 讨论(0)
提交回复
热议问题