gpt4 book ai didi

swift - Xcode/Firebase 改进搜索功能

转载 作者:行者123 更新时间:2023-11-28 15:19:19 25 4
gpt4 key购买 nike

我是 Xcode 和 firebase 的新手。我昨天做了这个搜索栏,但我只用它来搜索一件事(字符串)。现在我问如何搜索所有数据。数据来自 firebase,既是数字又是文本:

"Fornavn" - Text,
"Efternavn" - Text,
"Personnr" - Numbers

代码:

import UIKit
import FirebaseDatabase

class FindTableViewController: UITableViewController,
UISearchResultsUpdating {

@IBOutlet var FindTableView: UITableView!

let searchController = UISearchController(searchResultsController: nil)

var usersArray = [NSDictionary?]()
var filteredUsers = [NSDictionary?]()
var databaseRef = Database.database().reference()

override func viewDidLoad() {
super.viewDidLoad()

searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar

databaseRef.child("Buyers").queryOrdered(byChild: "personnr").observe(.childAdded, with: {(snapshot) in
self.usersArray.append(snapshot.value as? NSDictionary)

self.FindTableView.insertRows(at: [IndexPath(row:self.usersArray.count-1,section:0)], with: UITableViewRowAnimation.automatic)

})
{ (error) in
print(error.localizedDescription)
}

函数如下:

func updateSearchResults(for searchController: UISearchController) {
filterUsers(searchText: self.searchController.searchBar.text!)
}

func filterUsers (searchText:String) {
self.filteredUsers = self.usersArray.filter{ user in

let username = user!["Fornavn"] as? String

return(username?.lowercased().contains(searchText.lowercased()))!

}

tableView.reloadData()

}

关于如何搜索除“Fornavn”以外的文本的任何线索?

最佳答案

你可以这样做:

func filterUsers (searchText:String) {
self.filteredUsers = self.usersArray.filter{ user in
var searchResultForUserName = false
var searchResultForSecondSearch = false
var searchResultForThirdParam = false
if let username = user!["Fornavn"] as? String {
searchResultForUserName = username.lowercased().contains(searchText.lowercased())
}
if let secondSeachedStr = user!["Efternavn"] as? String {
searchResultForSecondSearch = secondSeachedStr.lowercased().contains(searchText.lowercased())
}
if let number = user!["Personnr"] as? String {

searchResultForThirdParam = number.lowercased().contains(searchText.lowercased())
}

return searchResultForUserName || searchResultForSecondSearch || searchResultForThirdParam


}

tableView.reloadData()

}

注意:请使用可选绑定(bind)来解包代码中的可选值

关于swift - Xcode/Firebase 改进搜索功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46293570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com