Skip to content

Instantly share code, notes, and snippets.

@gallaugher
Created June 21, 2018 02:01
Show Gist options
  • Select an option

  • Save gallaugher/d5829319189dd492cefed6bbb0487c17 to your computer and use it in GitHub Desktop.

Select an option

Save gallaugher/d5829319189dd492cefed6bbb0487c17 to your computer and use it in GitHub Desktop.
Spot.saveData
func saveData(spot: Spot, completed: @escaping (Bool) -> ()) {
let db = Firestore.firestore()
// Create the dictionary representing the data we want to save
let dataToSave = self.dictionary
// if we HAVE saved a record, we'll have a documentID
if self.documentID != "" {
let ref = db.collection("spots").document(spot.documentID).collection("reviews").document(self.documentID)
ref.setData(dataToSave) { (error) in
if let error = error {
print("*** ERROR: updating document \(self.documentID) in spot \(spot.documentID) \(error.localizedDescription)")
completed(false)
} else {
print("^^^ Document updated with ref ID \(ref.documentID)")
spot.updateAverageRating {
completed(true)
}
}
}
} else {
var ref: DocumentReference? = nil // Let firestore create the new documentID
ref = db.collection("spots").document(spot.documentID).collection("reviews").addDocument(data: dataToSave) { error in
if let error = error {
print("*** ERROR: creating new document in spot \(spot.documentID) for new review documentID \(error.localizedDescription)")
completed(false)
} else {
print("^^^ new document created with ref ID \(ref?.documentID ?? "unknown")")
spot.updateAverageRating {
completed(true)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment