Swift中如何在UILabel展示Google Places Autocomplete最近搜索及iOS端保存方法
Hey there! Let's tackle your two Google Places Autocomplete questions in Swift one by one:
Google Places Autocomplete doesn't provide a built-in way to fetch recent searches, so you'll need to handle storing and retrieving these records locally yourself. Here's a straightforward approach using UserDefaults (you could also use Core Data if you need more complex storage):
Step 1: Save selected places to local storage
Every time a user selects a place from the autocomplete results, save its details (like name or address) to UserDefaults, making sure to avoid duplicates and limit the number of stored records:
func saveRecentSearch(placeName: String) { // Retrieve existing recent searches, or start with an empty array var recentSearches = UserDefaults.standard.array(forKey: "RecentPlaces") as? [String] ?? [] // Remove duplicate if it exists, then add the new entry to the top if let duplicateIndex = recentSearches.firstIndex(of: placeName) { recentSearches.remove(at: duplicateIndex) } recentSearches.insert(placeName, at: 0) // Keep only the last 10 searches to avoid clutter if recentSearches.count > 10 { recentSearches.removeLast() } // Save the updated array back to UserDefaults UserDefaults.standard.set(recentSearches, forKey: "RecentPlaces") }
Step 2: Load and display recent searches in UILabel
Fetch the stored records, format them into a readable string, and set it to your UILabel:
func updateRecentSearchesLabel() { let recentSearches = UserDefaults.standard.array(forKey: "RecentPlaces") as? [String] ?? [] if recentSearches.isEmpty { recentSearchesLabel.text = "No recent searches yet" } else { let displayText = "Recent searches: \(recentSearches.joined(separator: ", "))" recentSearchesLabel.text = displayText } }
Don't forget to call updateRecentSearchesLabel() when your view loads, and saveRecentSearch(placeName:) right after the user selects a place from the autocomplete results.
Short answer: No, the official Google Places Autocomplete UI components (like GMSAutocompleteViewController) don't have built-in support for saving or displaying recent searches.
All management of recent search history needs to be implemented by you as the developer. The approach we covered in the first question (local storage with UserDefaults or Core Data) is the standard way to add this functionality. You can even extend the UI by adding a custom section above/below the autocomplete results to show your stored recent searches, letting users tap to re-select them quickly.
内容的提问来源于stack exchange,提问作者Biswajit Banik

