import SwiftUI
import Firebase
struct NotesView: View {
@State private var notes: [Note] = []
@State private var showingAddNote = false
@State private var newNoteText = ""
private var db = Firestore.firestore()
var body: some View {
NavigationView {
List {
ForEach(notes) { note in
Text(note.text)
}
.onDelete(perform: deleteNote)
}
.navigationTitle("Simple Firestore Notes")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
showingAddNote = true
}) {
Image(systemName: "plus")
}
.accessibilityLabel("Add note")
}
}
.onAppear(perform: listenToNotes)
.alert("Add New Note", isPresented: $showingAddNote, actions: {
TextField("Note text", text: $newNoteText)
Button("Save", action: addNote)
Button("Cancel", role: .cancel, action: {
newNoteText = ""
})
})
}
}
func listenToNotes() {
db.collection("notes").addSnapshotListener { snapshot, error in
guard let documents = snapshot?.documents else {
print("No documents")
return
}
notes = documents.map { doc in
let data = doc.data()
let text = data["text"] as? String ?? ""
return Note(id: doc.documentID, text: text)
}
}
}
func addNote() {
let trimmed = newNoteText.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return }
db.collection("notes").addDocument(data: ["text": trimmed])
newNoteText = ""
showingAddNote = false
}
func deleteNote(at offsets: IndexSet) {
offsets.forEach { index in
let note = notes[index]
db.collection("notes").document(note.id).delete()
}
}
}
struct Note: Identifiable {
var id: String
var text: String
}
struct NotesView_Previews: PreviewProvider {
static var previews: some View {
NotesView()
}
}This solution uses SwiftUI with Firebase Firestore to create a simple notes app.
We use addSnapshotListener to listen for real-time updates from the 'notes' collection. This keeps the list updated automatically.
The '+' button shows an alert with a text field to enter a new note. When saved, it adds a document to Firestore.
Notes are displayed in a list with swipe-to-delete enabled. Deleting removes the document from Firestore.
Accessibility label is added to the add button for screen readers.