2017-04-04 53 views
2

我使用this tutorial將數據添加到Firebase。它完美的作品。由於快照和持久性,它也可以離線工作。Firebase存儲圖像在Swift 3中的持久性

我還將圖片添加到this link的Firebase存儲中。這也適用,但不適用於持久性。我試圖從數據複製快照(第一個教程)來做到這一點,但FIRStorageReference沒有快照選項,據我所知。我怎樣才能做到這一點?

import Foundation 
import Firebase 
import FirebaseStorage 

struct MenuItemImage { 

let image: NSData 
let ref: FIRStorageReference? 
let key: String 



init(image: NSData, key: String = "") { 
    self.key = key 
    self.image = image 
    self.ref = nil 

} 

init(snapshot: FIRDataSnapshot) { // this should be something like FIRStoreSnapshot 
    key = snapshot.key 
    let snapshotValue = snapshot.value as! [String: AnyObject] 
    image = snapshotValue["image"] as! NSData 
    ref = snapshot.ref // errors as cannot assign value of tupe FIRDatabaseReference to type FIRStorageReference 
} 

func toAnyObject() -> Any { 
    return [ 
     "image": image 
    ] 
} 

} 
+0

你能詳細說明你的意思是「圖像持久性」嗎? –

+0

當然,對於正常的數據(字符串),我使用的代碼創建了一個數組,即使設備處於脫機狀態,該數組仍會保存字符串。 Firebase的行爲與NSUserDefaults或Core數據類似。沒有任何真正的設置。但是,圖片存儲在Firebase的其他區域,因此當設備處於脫機狀態時,字符串仍然顯示,但圖像消失(陣列爲空) – ThundercatChris

+1

Firebase存儲和Firebase數據庫是兩種不同的產品。 Firebase數據庫SDK可以爲您處理磁盤持久性。 Firebase存儲SDK不支持。要緩存從Firebase存儲獲得的圖片,您通常會使用第三方庫。看到任何這些:http://stackoverflow.com/search?q=%5Bfirebase-storage%5D%5Bios%5D+cache+images –

回答

1

使用FirebaseUI /存儲快照:添加到您的Podfile

pod 'FirebaseUI/Storage' 

然後,在你的代碼,以顯示和緩存的圖像做:

import FirebaseStorageUI 

let imgRef = Storage.storage().reference().child("images/\(blah)") 
myImageView.sd_setImage(with: imgRef)) 

就是這樣!如果使用相同的參考,圖像將在後臺獲取,並在下次緩存。