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

标签 ios swift firebase firebase-realtime-database

我正在创建一个库存应用程序,以便跟踪实验室中保存的元素。在实验室中,有不同的站点,其中包含不同的项目,正如您所看到的,这些项目在我的 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/

相关文章:

ios - 在 Swift 中带有超链接文本的 UITextView

arrays - 如何在 Swift 中分割字符串并保留分隔符?

ios - Firebase iOS 在后台和前台推送通知

iphone - 如何正确添加paypal sdk

ios - 如何在 `Quick Help` 的 Swift 注释中添加新行

ios - 如何使用ios将字符串编码为 "windows-1252"?

ios - Swift:不能用类型索引下标 [String:NSObject] 的值?

java - Firebase DataSnapshot,无法检索到正确的子列表

java - 无法从 firestore 中删除字段

ios - 使用另一个动态 UIImage mask UIImage