簡體   English   中英

如何從 firebase firestore 檢索圖像

[英]How to retrieve images from firebase firestore

任何人都可以幫助重寫此代碼以從 firebase firestore 檢索我的用戶圖像嗎? 我正在使用此代碼從 firebase 存儲中獲取我的圖像,圖像 url 存儲在 firestore 中,但我沒有取回我的圖像。 我只需要如何設置我的代碼以從 firebase firestore 檢索我的圖像 我正在使用 firebase 文檔,但我很難理解如何正確設置我的代碼以在 UI 中查看我的圖像

let db = Firestore.firestore()
let docRef = db.collection("users").document("ProfileImageUrl")

docRef.getDocument(source: .cache) { (document, error) in
  if let document = document {
    let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
    print("Cached document data: \(dataDescription)")
  } else {
    print("Document does not exist in cache")
  }
}

let storage =  Storage.storage().reference(forURL: "gs://fila-market-wetwork-809a6.appspot.com/ProfileImages/profilePic")


let localURL = URL(string: "https://firebasestorage.googleapis.com:443/v0/b/fila-market-wetwork-809a6.appspot.com/o/ProfileImages%2FprofilePic?alt=media&token=4cc88269-5740-49c6-ba40-f223f971ddb9")!

 
let downloadTask = storage.write(toFile: localURL) { url, error in
    if let error = error {
     
    } else {
     
    }
  }

你正在以錯誤的方式解決這個問題。 首先,您需要使用文檔的名稱(假設它是用戶的 ID)或通過查詢來獲取文檔。 我的示例假定文檔的名稱是用戶的 ID。 其次,您應該將圖像路徑作為文件名存儲在數據庫中,而不是整個 URL。想象一下,如果存儲 URL 在未來的 Firebase 更新中以任何方式發生變化,您將不得不重命名數據庫中的每個文檔。 第三,使用文件名構造存儲中文件的遠程路徑,並使用存儲 API 獲取它。 下面的例子假設了很多事情,比如你的存儲層次結構是如何組織的,你的用戶文檔的字段是如何命名的。

let userId = "cth2t0WD3e6tgrS6KpwJ"
let db = Firestore.firestore()
let docRef = db.collection("users").document(userId)

docRef.getDocument { (document, error) in
    if let doc = document,
       let filename = doc.get("imageFilename") as? String {
        let stg = Storage.storage()
        let remotePath  = "images/users/\(filename)"
        
        stg.reference(withPath: remotePath).getData(maxSize: 1_000_000) { (data, error) in
            if let remoteData = data,
               let downloadedImage = UIImage(data: remoteData) {
                // downloadedImage is your UIImage
            }
        }
    }
}

暫無
暫無

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

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