ChildbyAuto ID创建新的子引用

时间:2018-05-22 17:00:05

标签: ios swift uitableview firebase firebase-realtime-database

我只用了一个月的时间学习Swift和编程。所以请耐心等待。

我试图更改ChildbyAutoID创建的Child中的子值。我想要更改的值是isChecked Value。但它创造了一个新的孩子,并设置了那里的价值。

我的视图控制器

import UIKit
import FirebaseDatabase
import Firebase

class guestListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var guestListTableView: UITableView!



var guestListDBRef : DatabaseReference!
var guestListText = [AdminTextModel]()

override func viewDidLoad() {
    super.viewDidLoad()
    guestListDBRef = Database.database().reference().child("RSVP")
    guestListDBRef.queryOrdered(byChild: "name").observe(DataEventType.value, with: {(snapshot) in
        if snapshot.childrenCount > 0 {
        for guestListLabel in snapshot.children.allObjects as! [DataSnapshot] {
            let guestListTextObject = guestListLabel.value as? [String: AnyObject]
            let name = guestListTextObject?["name"]
            let date = guestListTextObject?["date"]
            let isChecked = guestListTextObject?["isChecked"]
            let key = guestListTextObject?["keyID"]
            let guestListTextLabels = AdminTextModel(key: key as! String?, name: name as! String?, date: date as! String?, isChecked: isChecked as! Bool? )
            self.guestListText.append(guestListTextLabels)
            self.guestListTableView.rowHeight = 45
            self.guestListTableView.reloadData()


            }
        }
    })

    // Do any additional setup after loading the view.
}





func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return guestListText.count

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let GuestListTextCell = tableView.dequeueReusableCell(withIdentifier: "guestList") as! GuestListTableViewCell
    let text: AdminTextModel
    text = guestListText[indexPath.row]

    GuestListTextCell.guestListNameLabel.text = text.name
    GuestListTextCell.guestListDateLabel.text = text.date

    if text.isChecked! {
        GuestListTextCell.accessoryType = .checkmark
    }else {
        GuestListTextCell.accessoryType = .none
    }
    return GuestListTextCell

}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let isChecked = self.guestListText[indexPath.row].isChecked!
    self.guestListText[indexPath.row].isChecked! = true
    let key = self.guestListText[indexPath.row].key



    Checkedservice.checkuncheck(key: key!, isChecked: isChecked) { (seccess) in
        guard seccess else { return }
        self.guestListText[indexPath.row].isChecked = true

        self.guestListTableView.reloadRows(at: [indexPath], with: .none)
        print("\(isChecked)")
        print(key!)
    }
}

struct Checkedservice {
    static func checkuncheck(key: String, isChecked: Bool, success: @escaping (Bool) -> Void) {

        let onlinesRef = Database.database().reference().child("RSVP").child(key).child("isChecked")
        onlinesRef.setValue(isChecked) {(error, _ ) in

            if let error = error {
                assertionFailure(error.localizedDescription)
                success(false)
            }
            success(true)
        }
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

我的自定义文字模型     进口基金会

class AdminTextModel {
var key: String?
var name: String?
var date: String?
var isChecked: Bool?
init(key: String?, name: String?, date: String?, isChecked: Bool?) {
    self.key = key
    self.name = name
    self.date = date
    self.isChecked = isChecked

    }
}

我的TableViewCell类

import UIKit

class GuestListTableViewCell: UITableViewCell {

@IBOutlet weak var guestListDateLabel: UILabel!
@IBOutlet weak var guestListNameLabel: UILabel!
override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
    }

}

这就是我写入数据库的方式。

@IBAction func rsvpButton(_ sender: Any) {

    let key = rsvpRef?.child("RSVP").childByAutoId().key
    let guestList = [
        "keyID": key,
        "name": nameTextField.text!,
        "date": dateTextField.text!,
        "isChecked": false] as [String : Any]
   rsvpRef?.child("RSVP").childByAutoId().setValue(guestList)
    if (nameTextField.text == nil) || dateTextField.text == nil {
        print("No RSVP Entered")
        self.dateTextField.text = nil
        self.nameTextField.text = nil
    }
    dateTextField.text = ""
    nameTextField.text = ""
}

我的最终目标是检查和取消选中单元格。但是当我重新加载视图时,检查和未检查的单元格仍然存在。非常感谢你!

我的火力架结构

My Firebase Structure

2 个答案:

答案 0 :(得分:0)

我认为你已经混淆了“如何在firebase中添加或更新记录”。让我们了解何时使用`childByAutoId()。根据firebase文档。

  

childByAutoId使用唯一键生成新的子位置   返回Firebase引用。这对孩子们很有用   Firebase数据库位置表示项目列表。

这意味着一旦您使用特定参考执行childByAutoId(),它将每次使用唯一键值创建新项目。

<强>解决方案:

我建议请使用下面的代码行来更新或添加值。

<强>更新

您也可以按照以下方式执行此操作。

  let key = rsvpRef?.child("RSVP").childByAutoId().key

  rsvpRef.child("key").observeSingleEvent(of: .value, with: { (snapshot) in
        if snapshot.hasChild(key){
            print("exist")
            let guestList = [
            "keyID": key,
            "name": nameTextField.text!,
            "date": dateTextField.text!,
            "isChecked": false] as [String : Any]

            rsvpRef?.child("RSVP").updateChildValues(guestList)
        }else{
            print("doesn't exist")
            rsvpRef?.child("RSVP").childByAutoId().setValue(guestList)
        }
    })

答案 1 :(得分:0)

A