以下是我遇到问题的代码。
共享:
// Firebase services
var database: FIRDatabase!
var storage: FIRStorage!
...
// Initialize Database, Auth, Storage
database = FIRDatabase.database()
storage = FIRStorage.storage()
...
// Initialize an array for your pictures
var picArray: [UIImage]()
上载:
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
// Create a UIImage, add it to the array
let pic = UIImage(data: data)
picArray.append(pic)
})
})
我几个月前一直试图使用@ Mike-McDonald最初发布的上述代码,从我的Firebase数据库中提取并附加一系列图像。我能够使用上面的内容成功上传图像,但是对于我的生活,我无法下载图像,也无法附加到图像阵列。
我没有收到任何错误 - 只是简单地下载"下载"代码似乎没有运行(我也尝试在控制台中验证这一点)。 Swift 3有几行不同,但我唯一不确定的是:
let storageRef = storage.referenceFromURL(downloadURL)
现在是
let storageRef = self.storage.reference(forURL: downloadURL)
对此有任何建议,或者如何使用带有Firebase的childadded观察者创建/追加图像数组,我们将不胜感激。谢谢!
答案 0 :(得分:0)
除了您必须更新为data(withMaxSize:completion)
,observe(_:with:)
并使用您已提及的reference(forURL:)
之外,我认为不错。所以你需要代码更新到这个:
let dbRef = database.reference().child("myFiles")
dbRef.observe(.childAdded, with: { (snaphot) in
// Get download URL from snapshot
let downloadURL = snapshot.value() as! String
// Create a storage reference from the URL
let storageRef = storage.reference(forURL: downloadURL)
// Download the data, assuming a max size of 1MB (you can change this as necessary)
storageRef.data(withMaxSize: 1 * 1024 * 1024) { (data, error) in
let pic = UIImage(data: data!)
picArray.append(pic)
}
})
答案 1 :(得分:0)
在我的案例中,我找到了答案。我没有将图像上传为数据。所以下载数据永远不会发生。它不会触发错误,它不会执行。以下是我所做的改变:
let fileData = NSData()
更改为:
let fileData = (UIImagePNGRepresentation(self.imagefile.image!)! as NSData?)!
它现在正常运作!