我强烈建议同时使用 Firebase 存储和 Firebase 实时数据库来存储 UUID -> URL 映射并“列出”文件。这实时数据库将处理离线用例 https://firebase.google.com/docs/database/ios/offline-capabilities也像 Core Data 一样,所以真的没有理由对 Core Data 或NSUserDefaults
。下面是一些显示这些部分如何交互的代码:
Shared:
// Firebase services
var database: FIRDatabase!
var storage: FIRStorage!
...
// Initialize Database, Auth, Storage
database = FIRDatabase.database()
storage = FIRStorage.storage()
Upload:
let fileData = NSData() // get data...
let storageRef = storage.reference().child("myFiles/myFile")
storageRef.putData(fileData).observeStatus(.Success) { (snapshot) in
// When the image has successfully uploaded, we get it's download URL
let downloadURL = snapshot.metadata?.downloadURL()?.absoluteString
// Write the download URL to the Realtime Database
let dbRef = database.reference().child("myFiles/myFile")
dbRef.setValue(downloadURL)
}
下载:
let dbRef = database.reference().child("myFiles")
dbRef.observeEventType(.ChildAdded, withBlock: { (snapshot) in
// Get download URL from snapshot
let downloadURL = snapshot.value() as! String
// Create a storage reference from the URL
let storageRef = storage.referenceFromURL(downloadURL)
// Download the data, assuming a max size of 1MB (you can change this as necessary)
storageRef.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in
// Do something with downloaded data...
})
})
有关更多信息,请参阅从零到应用:使用 Firebase 进行开发 https://www.youtube.com/watch?v=xAsvwy1-oxE,它是相关源代码 https://gist.github.com/mcdonamp/cc45567cd95ba2a62017cb21e891effd,了解如何执行此操作的实际示例。