gpt4 book ai didi

ios - 如何在 Firebase 中显示 autoID 子项下保存的数据?

转载 作者:行者123 更新时间:2023-11-30 12:51:10 25 4
gpt4 key购买 nike

我正在创建一个库存应用程序,以便跟踪实验室中保存的元素。在实验室中,有不同的站点,其中包含不同的项目,正如您所看到的,这些项目在我的 Firebase 数据库中结构正确。

Firebase Database

Iphone Simulator

当我尝试从 tableCell 中删除特定项目时,我的问题出现了。我可以从 UI 中删除它,但在 firebase 中数据仍然保留。我做了无数的研究,但找不到与这个特定问题相关的任何内容。

数据服务类

let DB_BASE = FIRDatabase.database().reference().child("laboratory")       //contains the root of our database
let STORAGE_BASE = FIRStorage.storage().reference()

class DataService {

static let ds = DataService()

//DB References
private var _REF_BASE = DB_BASE
private var _REF_STATION = DB_BASE.child("stations")
private var _REF_USERS = DB_BASE.child("users")

//Storage Reference
private var _REF_ITEM_IMAGE = STORAGE_BASE.child("item-pics")

var REF_BASE: FIRDatabaseReference {
return _REF_BASE
}

var REF_STATION: FIRDatabaseReference {
return _REF_STATION
}

var REF_USERS: FIRDatabaseReference {
return _REF_USERS
}

var REF_ITEM_IMAGES: FIRStorageReference {
return _REF_ITEM_IMAGE
}

//creating a new user into the firebase database

func createFirebaseDBUser(_ uid: String, userData: Dictionary<String, String>) {
REF_USERS.child(uid).updateChildValues(userData)
}
}

库存 View Controller

import UIKit
import Firebase

class InventoryViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

var items = [Item]()

private var _station: Station!
private var _item: Item!

var sortIndex = 3

var imagePicker: UIImagePickerController!
static var imageCache: NSCache<NSString, UIImage> = NSCache()
var imageSelected = false

@IBOutlet weak var itemImageToAdd: UIImageView!
@IBOutlet weak var objectTextInput: UITextField!
@IBOutlet weak var brandTextInput: UITextField!
@IBOutlet weak var unitTextInput: UITextField!
@IBOutlet weak var amountTextInput: UITextField!
@IBOutlet weak var tableView: UITableView!
@IBOutlet var addItemView: UIView!
@IBOutlet weak var currentStationLabel: UILabel!

var station: Station {
get {
return _station
} set {
_station = newValue
}
}

override func viewDidLoad() {
super.viewDidLoad()

var currentStationName = station.title

currentStationLabel.text = currentStationName

self.items = []

let currentStation = station.title
let stationRef = DataService.ds.REF_STATION.child(currentStation!)
let inventoryRef = stationRef.child("inventory")

tableView.delegate = self
tableView.dataSource = self

imagePicker = UIImagePickerController()
imagePicker.allowsEditing = true
imagePicker.delegate = self

inventoryRef.observe(.value, with: { (snapshot) in
print(snapshot.value!)

self.items = []

if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {

for snap in snapshot {

print("SNAP: \(snap)")
if let itemDict = snap.value as? Dictionary<String, AnyObject> {

let key = snap.key
let item = Item(itemKey: key,
itemData: itemDict)
self.items.append(item)
}
}
}
self.tableView.reloadData()
})


}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = items[indexPath.row]

if let cell = tableView.dequeueReusableCell(withIdentifier: "inventoryTableCell", for: indexPath) as? ItemCell {

if let img = InventoryViewController.imageCache.object(forKey: NSString(string: item.imageURL!)) {

cell.updateItemUI(item: item, img: img)

} else {

cell.updateItemUI(item: item)
}

return cell

} else {

return ItemCell()
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}

func postToFirebase(itemImageURL: String) {

let post: Dictionary<String, AnyObject> = [
"objectLabel": objectTextInput.text! as AnyObject,
"brandLabel": brandTextInput.text! as AnyObject,
"unitLabel": unitTextInput.text! as AnyObject,
"amountLabel": amountTextInput.text! as AnyObject,

//post elsewhere as an image for future reference
"itemImageURL": itemImageURL as AnyObject,

]
let stationText = _station.title
let stationRef = DataService.ds.REF_STATION.child(stationText!)
let inventoryRef = stationRef.child("inventory")

let firebasePost = inventoryRef.childByAutoId()
firebasePost.setValue(post)

objectTextInput.text = ""
brandTextInput.text = ""
unitTextInput.text = ""
amountTextInput.text = ""
imageSelected = false

tableView.reloadData()
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {

itemImageToAdd.image = image
imageSelected = true
} else {

print("Please select a valid image")
}

imagePicker.dismiss(animated: true, completion: nil)
}

@IBAction func backToStations(_ sender: Any) {

performSegue(withIdentifier: "backToStations", sender: nil)

}

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}

func tableView(tableView: (UITableView!), commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: (NSIndexPath!)) {

}

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

let currentStation = station.title
let stationRef = DataService.ds.REF_STATION.child(currentStation!)
let inventoryRef = stationRef.child("inventory")

var deleteAction = UITableViewRowAction(style: .default, title: "Delete") {action in

//Insert code to delete values from Firebase
self.items.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath as IndexPath], with: .fade)

}

var editAction = UITableViewRowAction(style: .normal, title: "Edit") { action in

}

return [deleteAction, editAction]
}
}

我的思考过程是在删除时调用 self_items.key 引用特定 tableCell 行的当前键。从那里我将使用当前的 key (即 autoID)并以这种方式删除该值。不幸的是,这会导致程序崩溃并出现致命的零错误。

最佳答案

我发现解决此问题的最佳方法是在删除操作中,从 Firebase 中删除该对象。不要从这里更改表格 View 。

然后在数据监听器中,检查数据何时返回为已删除(或 NULL),然后将其从 TableView 数据源数组中删除并更新 TableView 。

关于ios - 如何在 Firebase 中显示 autoID 子项下保存的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40954546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com