Created
December 1, 2025 16:37
-
-
Save gallaugher/3a677341e1cd9df5faf9bbad00c0250a to your computer and use it in GitHub Desktop.
PlaceViewModel.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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