Skip to content

Instantly share code, notes, and snippets.

@gallaugher
Created December 1, 2025 16:37
Show Gist options
  • Select an option

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

Select an option

Save gallaugher/3a677341e1cd9df5faf9bbad00c0250a to your computer and use it in GitHub Desktop.
PlaceViewModel.swift
import FirebaseFirestore
@Observable
class PlaceViewModel {
static func savePlace(place: Place) async -> String? {
let db = Firestore.firestore()
if let id = place.id { // if true, the place exists
do {
try db.collection("places").document(id).setData(from: place)
print("😎 Data updated successfully!")
return id
} catch {
print("😑 ERROR: Could not update data in 'places'. \(error.localizedDescription)")
return id
}
} else { // This must be a new place, with no id, so we'll add / create the document
do {
let docref = try db.collection("places").addDocument(from: place)
print("🐣 Data added successfully!")
return docref.documentID
} catch {
print("😑 ERROR: Could not create a new place in 'places'. \(error.localizedDescription)")
return nil
}
}
}
static func deletePlace(place: Place) {
let db = Firestore.firestore()
guard let id = place.id else {
print("😑 ERROR: Tried to delete a place with no id!")
return
}
Task {
do {
try await db.collection("places").document(id).delete()
print("πŸ—‘οΈ Successfully deleted!")
} catch {
print("😑 ERROR: Could not delete document id \(id). \(error.localizedDescription)!")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment