Firebase如何使用childByAutoId()保存多个孩子

时间:2017-10-13 18:43:30

标签: ios swift firebase firebase-realtime-database

我需要保存一个对象,并在完成后将autoId的子项添加到同一个对象。我目前正在保存第一个对象,并在循环内添加autoId的子项。我想知道是否有更有效的方法来做到这一点?

let data: [String: Any] = [
  "one": 1,
  "two": 2,
  "aboutS": "yeeah",
  ]

//Data to be saved with auto id after inital data saved
let mediaMetaData: [[String: Any]] = [
  ["path": "nda.mov", "type": "009"],
  ["path": "nda.mov", "type": "009"]
]

ref.getUserSkillDatabasePath(authUser).childByAutoId().setValue(data, withCompletionBlock: {
  error, dbReference in
  if error != nil {
    print(error as Any)
  }
  let mediaUploadGroup = DispatchGroup()

  //Loop through mediaMetaData and save children using auto id
  // Wish to save all children with auto id objects at once?
  mediaMetaData.forEach {
    meta in
    mediaUploadGroup.enter()
    dbReference.child("media").childByAutoId().setValue(meta, withCompletionBlock: {_,_ in
      mediaUploadGroup.leave()
    })
  }
  mediaUploadGroup.notify(queue: .main, execute: {
    completion(error)
  })
})

1 个答案:

答案 0 :(得分:4)

您可以尝试使用updateChildValues进行原子写入。所以做这样的事情应该会达到同样的结果:

let data: [String: Any] = [
    "one": 1,
    "two": 2,
    "aboutS": "yeeah",
    ]

let mediaMetaData: [[String: Any]] = [
    ["path": "nda.mov", "type": "009"],
    ["path": "nda.mov", "type": "009"]
]

let userRef = ref.getUserSkillDatabasePath(authUser)
let userKey = userRef.childByAutoId().key

var dataObject: [String: Any] = data
for meta in mediaMetaData {
    let mediaKey = userRef.child(userKey).child("media").childByAutoId().key
    dataObject["/media/\(mediaKey)"] = meta
}

userRef.child(userKey).updateChildValues(dataObject, withCompletionBlock: { _,_ in
    print("Success")
})