【问题标题】:How to upload multiple image on firebase using swift?如何使用swift在firebase上上传多张图片?
【发布时间】:2018-09-30 17:33:22
【问题描述】:

我只想使用 swift 在 firebase 上上传多张图片。我现在正在上传一张图片,但无法上传多张图片。这是我的代码

let photoIdString = NSUUID().uuidString
let storageRef = Storage.storage().reference(forURL: Config.STORAGE_ROOF_REF).child("posts").child(photoIdString)
storageRef.putData(imageData, metadata: nil,completion: {(metadata,error) in

       if error != nil {
            return
       }
       let photoUrl = metadata?.downloadURL()?.absoluteString
       let ref = Database.database().reference()
       let postReference = ref.child("posts")
       let newPostId = postReference.childByAutoId().key
       let newPostReference = postReference.child(newPostId)
       newPostReference.setValue(["photoUrl":photoUrl,"caption":self.textView.text!]) 

【问题讨论】:

标签: ios swift firebase firebase-storage


【解决方案1】:

目前没有直接的API来批量上传/下载文件。我们不能使用循环,因为所有任务都执行asynchronously。我们能做的就是使用递归函数。

核心逻辑

let images = [image1, image2, image3, image4]
func uploadImage(forIndex index: Int) {
    if index < images.count {
        /// Perform uploading
        /// After successfully uploading call this method again by increment the **index = index + 1**
        return;
    }

    /// All images have been uploaded successfully
}

完整代码示例

1.我为文件上传创建了一个自定义类

import UIKit
import Firebase

class FirFile: NSObject {

    /// Singleton instance
    static let shared: FirFile = FirFile()

    /// Path
    let kFirFileStorageRef = Storage.storage().reference().child("Files")

    /// Current uploading task
    var currentUploadTask: StorageUploadTask?

    func upload(data: Data,
                withName fileName: String,
                block: @escaping (_ url: String?) -> Void) {

        // Create a reference to the file you want to upload
        let fileRef = kFirFileStorageRef.child(fileName)

        /// Start uploading
        upload(data: data, withName: fileName, atPath: fileRef) { (url) in
            block(url)
        }
    }

    func upload(data: Data,
                withName fileName: String,
                atPath path:StorageReference,
                block: @escaping (_ url: String?) -> Void) {

        // Upload the file to the path
        self.currentUploadTask = path.putData(data, metadata: nil) { (metaData, error) in
            let url = metaData?.downloadURL()?.absoluteString
            block(url)
        }
    }

    func cancel() {
        self.currentUploadTask?.cancel()
    }
}

2。这里我们如何使用这个

首先为 main 函数创建一个完成块,它会在所有图像上传成功时通知您。

/// This is your images array
let images = [image1, image2, image3, image4]

/// Here is the completion block
typealias FileCompletionBlock = () -> Void
var block: FileCompletionBlock?

下面是两个函数,第一个是初始函数,它将开始上传,第二个函数是递归,如果有下一张图片可以上传,它会调用自己。

func startUploading(completion: @escaping FileCompletionBlock) {
     if images.count == 0 {
        completion()
        return;
     }

     block = completion
     uploadImage(forIndex: 0)
}

func uploadImage(forIndex index:Int) {

     if index < images.count {
          /// Perform uploading
          let data = UIImagePNGRepresentation(images[index])!
          let fileName = String(format: "%@.png", "yourUniqueFileName")

          FirFile.shared.upload(data: data, withName: fileName, block: { (url) in
              /// After successfully uploading call this method again by increment the **index = index + 1**
              print(url ?? "Couldn't not upload. You can either check the error or just skip this.")
              self.uploadImage(forIndex: index + 1)
           })
        return;
      }

      if block != nil {
         block!()
      }
}

最后是带有完成块的主函数

startUploading {
    /// All the images have been uploaded successfully.
}

编辑新 Firebase 的“上传”功能:

唯一的区别是获取下载 url 的方式。这是new Firebase doc 。

func upload(data: Data,
            withName fileName: String,
            atPath path:StorageReference,
            block: @escaping (_ url: String?) -> Void) {

    // Upload the file to the path
    self.currentUploadTask = path.putData(data, metadata: nil) { (metaData, error) in
         guard let metadata = metadata else {
              // Uh-oh, an error occurred!
              block(nil)
              return
         }
         // Metadata contains file metadata such as size, content-type.
         // let size = metadata.size
         // You can also access to download URL after upload.
         path.downloadURL { (url, error) in
              guard let downloadURL = url else {
                 // Uh-oh, an error occurred!
                 block(nil)
                 return
              }
             block(url)
         }
    }
}

【讨论】:

  • 先生,请详细说明
  • 您能否更新您的答案。 'StorageMetadata'类型的值没有成员'downloadURL'错误Firebase 5
  • @Nitesh 按要求更新。
  • 泰国很棒。谢谢@Tiger bhai...!
猜你喜欢
  • 2020-08-14
  • 2017-06-29
  • 2020-02-16
  • 2020-06-24
  • 2018-05-21
  • 2016-10-12
  • 2022-01-20
  • 2020-12-05
  • 1970-01-01
相关资源
最近更新 更多