I have only found answers regarding the real time database rather than firestore, I want to be able to have a user search for a name and get back all the matching documents. I am using a textfield that calls a function onChange of the textfield text (also limits to one call every 2 seconds to decrease amount of calls).
struct StoryModel: Identifiable, Codable, Hashable {
var id: String
var isLive: Bool?
var name: String?
var description: String?
private enum CodingKeys: String, CodingKey {
case id
case isLive
case name
case description
}
}
This is how every document in the same collection is modeled. I want to only get the documents where field "name" matches the textfield search text. I have tried this so far:
@Published var storiesSearchText: String = ""
@Published var searchedStories: [StoryModel] = []
private lazy var storiesDataCollection = Firestore.firestore().collection("Stories")
public func getSearchedStories() {
print(storiesSearchText)
self.storiesDataCollection
.whereField("isLive", isEqualTo: true)
.whereField("name", in: [self.storiesSearchText])
.getDocuments { (snapshot, error) in
if let documents = snapshot?.documents {
for document in documents {
print(document)
if let story = try? document.data(as: StoryModel.self) {
self.searchedStories.append(story)
}
}
} else if let error = error {
print("Error getting search stories: \(error)")
}
}
}
The only way I can get the code to work is to use whereField isEqualTo but this would only work when the user types the name exactly and then searches, which does not give live results as the user searches. How can I achieve this live feedback of search results from my firestore collection?
Edit: None of these questions have live feedback, they are not answering my question. And most of them are not even in Swift. Please leave the link as a comment first before closing this post. I have yet to find an answer for the specific requirements of this question.
How to search in Firestore database?
Firestore - implementing search fields
How to search text in Flutter using Firestore
Google Firestore: Query on substring of a property value (text search)