簡體   English   中英

如何完成將圖像上傳到Firebase存儲,然后將imageUrl保存到Firebase數據庫

[英]How to finish the upload of images to Firebase Storage and then save the imageUrl to the Firebase Database

我沒有找到滿意的答案,希望您有任何想法。 我想將圖像上傳到Firebase存儲並將imageUrls保存到Firebase數據庫。

     var imageUrls = [String]()

     func uploadImagesToStorage(imagesArray: [UIImage]) {


    for i in imagesArray {

        guard let uploadData = UIImageJPEGRepresentation(i, 0.3) else { return }
        let fileName = NSUUID().uuidString

         FIRStorage.storage().reference().child("post_Images").child(fileName).put(uploadData, metadata: nil) { (metadata, err) in

            if let err = err {
            return
            }

            guard let profileImageUrl = metadata?.downloadURL()?.absoluteString else { return }
            self.imageUrls.append(profileImageUrl)

        }.resume()

  } //..End loop
       saveToDatabaseWithImageUrl(imageUrls: imageUrls)

上載圖像可以使用uploadImagesToStorage(imagesArray:[UIImage])方法。 此方法獲取一個數組作為參數,其中包含我要上傳的圖像。 在上傳圖像時,我正在從firebase給我的元數據中下載imageUrl信息,並將該imageUrl保存到imageUrls數組中。 為了保存每個圖像的imageUrl信息,必須進行for循環。 當上傳圖像並在imageUrls數組中填充了imageUrl信息時,我調用函數func saveToDatabaseWithImageUrl(imageUrls:[String])將imageUrls保存到數據庫中。 檢查Firebase我看到圖像已保存到Firebase存儲中,但是imageUrls沒有保存到Firebase數據庫中。 在調試我的代碼時,我發現這種現象的原因是,在上傳圖像時,代碼跳到了下一行。 因此,它將使用一個空的imageUrls數組調用saveToDatabaseWithImageUrls。 我閱讀了[Documentation] [1],並嘗試使用.resume()方法管理上傳。 仍然跳轉到saveToDatabaseWithImageUrl方法。 我不知道如何保證上傳完成,然后執行下一行代碼。 謝謝你的幫助。

發生這種情況是因為您的.child("post_Images").child(fileName).put調用異步進行。 其余代碼同步。 因此,您for開始上傳照片,然后將URL保存到數據庫中,但是URL為空,因為您無需等待完成上傳。

我給你一個基於DispathGroup的完美解決方案

//Create DispatchGroup
let fetchGroup = DispatchGroup()

for i in imagesArray {
    guard let uploadData = UIImageJPEGRepresentation(i, 0.3) else { return }

    let fileName = NSUUID().uuidString
    //Before every iteration enter to group
    fetchGroup.enter()        
    FIRStorage.storage().reference().child("post_Images").child(fileName).put(uploadData, metadata: nil) { (metadata, err) in
        if let err = err {
        fetchGroup.leave()
        return
        }

        guard let profileImageUrl = metadata?.downloadURL()?.absoluteString else { return }
        self.imageUrls.append(profileImageUrl)
        //after every completion asynchronously task leave the group
        fetchGroup.leave()
    }.resume()
}

並知道id魔術

fetchGroup.notify(queue: DispatchQueue.main) {
    //this code will call when number of enter of group will be equal to number of leaves from group
    //save your url here
    saveToDatabaseWithImageUrl(imageUrls: imageUrls)
}

此解決方案不會阻塞線程,此處所有內容均異步運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM