访问childAutoID以更新Firebase

时间:2017-09-21 02:41:10

标签: ios swift firebase firebase-realtime-database

为了填充我的tableView,我将项目(从结构创建)附加到本地数组:

func loadList() {
        var newAnnotations: [AnnotationListItem] = []
    if let uid = Auth.auth().currentUser?.uid {
        uidRef.child(uid).child("annotations").queryOrderedByKey().observeSingleEvent(of: .value, with: {snapshot in

            for item in snapshot.children {
                let annotationItem = AnnotationListItem(snapshot: item as! DataSnapshot)
                newAnnotations.append(annotationItem)
            }
            annotationList = newAnnotations
            self.tableView.reloadSections([0], with: .fade)
        })
    }
}

当我点击特定行时,我将被带到DetailViewController,其中只有一个UITextView(命名注释)。显示的UITextView.text基于所选的indexPath.row,并且从数组中检索“notes”值。现在,用户可以键入一些文本,完成后,将调用textViewDidEndEditing函数:

func textViewDidEndEditing(_ textView: UITextView) {
    notes.resignFirstResponder()
    navigationItem.rightBarButtonItem = nil

    let newNotes = self.notes.text
    print(newNotes!)
}

现在,我想在我的JSON中updateChildValuesnewNotes到子节点“notes”:

"users" : {
  "gI5dKGOX7NZ5UBqeTdtu30Ze9wG3" : {
    "annotations" : {
      "-KuWIRBARv7osWr3XDZz" : {
        "annotationSubtitle" : "1 Cupertino CA",
        "annotationTitle" : "Apple Infinite Loop",
        "notes" : "Does it work?!",
    }

如何访问所选的autoID,以便我可以更新特定的notes节点。到目前为止,我所拥有的最好的是:

guard let uid = Auth.auth().currentUser?.uid else { return }
    uidRef.child(uid).child("annotations").(somehow access the specific childID).updateChildValues(["notes": newNotes])

任何帮助将不胜感激。提前致谢

更新

创建annotationListItem结构:

struct AnnotationListItem {

let key: String?
var annotationTitle: String?
let annotationSubtitle: String?
let notes: String?
let ref: DatabaseReference?

init(key: String = "", annotationTitle: String, annotationSubtitle: String, notes: String) {
    self.key = key
    self.annotationTitle = annotationTitle
    self.annotationSubtitle = annotationSubtitle
    self.notes = notes
    self.ref = nil
}

init(snapshot: DataSnapshot) {
    key = snapshot.key
    let snapshotValue = snapshot.value as! [String: AnyObject]
    annotationTitle = snapshotValue["annotationTitle"] as? String
    annotationSubtitle = snapshotValue["annotationSubtitle"] as? String
    notes = snapshotValue["notes"] as? String
    ref = snapshot.ref
}

init(Dictionary: [String: AnyObject]) {
    self.key = Dictionary["key"] as? String
    self.annotationTitle = Dictionary["annotationTitle"] as? String
    self.annotationSubtitle = Dictionary["annotationSubtitle"] as? String
    self.notes = Dictionary["notes"] as? String
    self.ref = nil
}

func toAnyObject() -> Any {
    return [
        "annotationTitle": annotationTitle as Any,
        "annotationSubtitle": annotationSubtitle as Any,
        "notes": notes as Any
    ]
}
}

更新

这就是创建annotationListItem以存储在Firebase中的方式:

// Using the current user’s data, create a new AnnotationListItem that is not completed by default
    let uid = Auth.auth().currentUser?.uid
    guard let email = Auth.auth().currentUser?.email else { return }
    let title = placemark.name
    let subtitle = annotation.subtitle
    let notes = ""

    // declare variables
    let annotationListItem = AnnotationListItem(
        annotationTitle: title!,
        annotationSubtitle: subtitle!,
        notes: notes)

    // Add the annotation under their UID
    let userAnnotationItemRef = uidRef.child(uid!).child("annotations").childByAutoId()
    userAnnotationItemRef.setValue(annotationListItem.toAnyObject())

2 个答案:

答案 0 :(得分:2)

我认为你只需要这样做:(因为你已经将音符声明为全局)

 guard let uid = Auth.auth().currentUser?.uid else { return } 
uidRef.child(uid).child("annotations").(note.key).updateChildValues(["notes": newNotes])

在您更改笔记的方法内

答案 1 :(得分:0)

如果我没弄错的话你是在创建一个自定义对象的数组?

var newAnnotations: [AnnotationListItem] = []

您可以执行以下操作:var newAnnotations: [(key: String, value: [String : Any])] = []Any仅当您要StringsIntegers等时才会这样做。如果它只是{{1}然后将其指定为String

在您String的{​​{1}}中访问密钥为:newAnnotations[indexPath.row].key。访问值为:cellForRowAtIndex

您可以拥有一个单独的数组来保存密钥,只需将其与您的人口同时附加:

tableView

你可以做的另一件事是在你的firebase调用中增加一个级别:

newAnnotations[indexPath.row].value["NAME"]

然后当你选择一行时:let selectedItem = for item in snapshot.children { guard let itemSnapshot = task as? FDataSnapshot else { continue } let id = task.key //This is the ID let annotationItem = AnnotationListItem(snapshot: item as! DataSnapshot) newAnnotations.append(annotationItem) } //这是你传递给viewController的ID。