使用Google Firebase同时上传多张图片

时间:2016-06-12 00:33:53

标签: ios swift firebase firebase-storage

我在Swift iOS项目中使用Google Firebase。我有我的应用程序的一部分,用户从他们的设备中选择多张照片进行上传。我正在尝试找到将他们一次选择的所有照片上传到Firebase存储的最佳做法。我知道如何上传一张照片。

我查看了文档但没有看到任何关于上传多个NSData对象的方法,那么我是否只运行for循环并单独上传每个图像?

谢谢!所有反馈都表示赞赏。

2 个答案:

答案 0 :(得分:12)

Swift 3 这就是我将多个图片上传到Firebase的方式。我正在计算成功上传,如果它等于提供的图像数量,那就是当我调用完成处理程序时。

不确定这是否是最佳做法,但它确实有效!

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
            }
          }
        }
    }

}

用法

let arrayOfImages : [UIImage] = [Image1, Image2, Image3]
UploadImages.saveImages(imagesArray: arrayOfImages)

答案 1 :(得分:0)

@FrankVanPuffellen在评论中回答......

“你确实只是循环并单独上传它们。如果你一次上传一个,你的iOS用户也会很感激,这样他们就可以在中途中止上传而不会丢失所有图片的进度。” - 弗兰克范普弗伦