我有一个表格 View ,当单击一个单元格(类别)时,它会显示一个带有 2 个选项卡的选项卡栏。第一个选项卡是相机,第二个选项卡是包含一些图像的图像库。
主要的约束是,当图像在特定单元格(类别)中更新时,它可能属于另一个类别,也应该在那里更新。
现在,我将实时数据库和存储设置为模拟类别的目录。当更新图像时(在特定单元格内),它会更新存储中的图像(通过利用单元格的属性)并在数据库中创建一个指向直接下载链接的指针。
这种方法的问题在于它根本不处理主要约束,并且最终会存储同一图像的多个副本。
这是我将图片上传到 Firebase 的代码
func savePhotoStorage(){
//replace spaces with _
let title = textField.text!.replacingOccurrences(of: " ", with: "_")
let imageRef = storageRef.child(self.section).child(self.AU).child("Photos").child(title + ".jpg")
if let dataImage = UIImageJPEGRepresentation(imageView.image!, 1){
let uploadTask = imageRef.putData(dataImage, metadata: nil, completion : { (metadata, error) in
if error != nil{
print(error)
return
}
if let downloadPath = metadata?.downloadURL()?.absoluteString{
self.pushtoDB(path: downloadPath,type:"Photos",title: title)
print(metadata?.downloadURL())
}
else{
print("No metadata available")
}
})
uploadTask.resume()
textField.text = ""
//captureSession.stopRunning()
//previewLayer.removeFromSuperlayer()
}
}
func pushtoDB(path : String, type:String,title:String){
databaseRef.child(section).child(AU).child(type).child(title).setValue(path)
}
这是我在上传图片时更新图库的代码
func loadImages(){
databaseHandle = databaseRef.observe(DataEventType.childAdded, with: { (snapshot) in
if let _ = snapshot.value as? String {
let imageView = UIImageView()
let url = URL(string: snapshot.value as! String)
let resource = ImageResource(downloadURL: url!, cacheKey: snapshot.value as? String)
imageView.kf.indicatorType = .activity
imageView.kf.setImage(with: resource)
imageView.contentMode = .scaleAspectFit
let label = UILabel()
//label.text = imageArray[i]
let title = snapshot.key.replacingOccurrences(of: "_", with: " ")
label.text = title
label.font = UIFont(name: "ScienceFair", size: 30)
label.textAlignment = .center
label.textColor = UIColor.white
label.backgroundColor = UIColor.black
label.sizeToFit()
let width = UIScreen.main.nativeBounds.width/2
let xPosition = width * CGFloat(self.i)
imageView.frame = CGRect(x: xPosition, y: 0, width: self.mainScrollView.frame.width, height: self.mainScrollView.frame.height)
label.frame = CGRect(x: xPosition, y: 10, width: label.intrinsicContentSize.width, height: label.intrinsicContentSize.height)
label.center = CGPoint(x: xPosition+self.view.center.x, y: 30)
self.mainScrollView.contentSize.width = self.mainScrollView.frame.width * CGFloat(self.i+1)
self.mainScrollView.addSubview(imageView)
self.mainScrollView.addSubview(label)
self.mainScrollView.autoresizingMask = .flexibleHeight
self.i = self.i+1
}
})
}
对我来说最完美的用例是,如果有某种方法可以将监听器附加到 Firebase 存储,如果文件位置更新为新的下载链接,实时数据库中所有指向旧下载的子项链接现在指向新的下载链接。
到目前为止,我还没有找到这种类型的监听器,那么我应该如何配置我的存储和数据库,以便上述情况发生并且我不必上传相同图像的副本?
最佳答案
您只需要在存储中保存一份图像副本,并在您的数据库中简单地为它创建多个引用,所有这些都使用相同的下载 url。然后,您可以使用 database.ref('images').orderByChild(databaseURL).equalTo(imageDatabaseURL)
关于ios - 在多个地方显示相同图像的正确 Firebase 设计是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49057400/