微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何一次调用childByAutoId? 迅速

如何解决如何一次调用childByAutoId? 迅速

由于我一键上传多个图像到Firebase,所以我创建了一个循环,直到所有图像都上传为止。将图片上传到存储设备后,我想将网址保存在实时Firebase中。这就是我所拥有的:

@IBAction func postFinalButton(_ sender: Any) {
        ProgressHUD.show()
        ProgressHUD.animationType = .circleRotateChase
        ProgressHUD.colorAnimation = #colorLiteral(red: 0.337254902,green: 0.6156862745,blue: 0.9803921569,alpha: 1)
        ProgressHUD.colorHUD = #colorLiteral(red: 1,green: 1,blue: 1,alpha: 0)
        startUploading(completion: {
            print("Done!!!")
            ProgressHUD.showSucceed()
        })
    }
    func sendDataToDatabase(photoUrl: String,ref: DatabaseReference,index: Int) {
     print("okbud")
      let name = "photoUrl"+String(index)
        ref.setValue([name: photoUrl,"caption": "buddy"],withCompletionBlock: {
        (error,ref) in
        if error != nil {
            ProgressHUD.showError(error?.localizedDescription)
            return
        }
        ProgressHUD.showSucceed()
      })
    }
    func startUploading(completion: @escaping FileCompletionBlock) {
         if ImagesOnClick.count == 0 {
            completion()
            return;
         }

         block = completion
         uploadImage(forIndex: 0)
    }

    func uploadImage(forIndex index:Int) {
        let ref = Database.database().reference()
        let postsReference = ref.child("posts")
        let newImagesRef = postsReference.childByAutoId()

         if index < ImagesOnClick.count {
              /// Perform uploading
             let data = ImagesOnClick[index]!.pngData()
             let fileName = String(format: "%@.png",String(newImagesRef.key!))

            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.sendDataToDatabase(photoUrl: url!,ref: newImagesRef,index: index)
                  self.uploadImage(forIndex: index + 1)
               })
            return;
          }

          if block != nil {
             block!()
          }
    }
    
class FirFile: NSObject {

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

    /// Path
    let kFirFileStorageRef = Storage.storage().reference(forURL: "gs://loginpage-227bd.appspot.com")

    /// 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,atPath: fileRef) { (url) in
            block(url)
        }
    }
    func upload(data: Data,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(downloadURL.absoluteString)
             }
        }
    }

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

但是图像的存储方式如下:

enter image description here

当我希望将它们像这样存储时:

enter image description here

我该怎么做?

解决方法

我声明了一个变数:

var childByAutoId = String()

然后,当viewDidLoad我将函数childByAutoId()分配给变量childByAutoId

        let ref = Database.database().reference()
        let postsReference = ref.child("posts")
        let newImagesRef = postsReference.childByAutoId()
        childByAutoId = newImagesRef.key!

最后:

        let ref = Database.database().reference()
        let postsReference = ref.child("posts")
        let newImagesRef = postsReference.child(childByAutoId)
self.sendDataToDatabase(photoUrl: url!,ref: newImagesRef,index: index)

如果有任何疑问,请评论!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。