搜索用户:仅在键入至少两个字母时才加载数据库,并且也仅加载相关数据

时间:2019-01-03 18:51:08

标签: swift firebase uitableview firebase-realtime-database uisearchcontroller

我对这个问题感到非常沮丧,这已经有很长时间了。我的“ searchUsers”函数的唯一工作方式是将其放入ViewDidLoad中,然后将.count更改为等于或小于0(默认情况下为0)。

但是就目前而言(我认为它应该如何工作),搜索功能就可以了。

我想要做的是:

1。仅在用户键入至少两个字母时才为用户启动Firebase搜索(因此,仅在用户开始键入时才搜索用户,并且仅显示和加载相关数据,而不在数据库中加载每个用户)。

2。还要更新表格视图以及过滤搜索。

当用户键入两个字母时,如何才能使它开始加载数据库,并且仅加载正确的用户名。说如果一个用户键入“ Ma”,那么它将加载数据库(因为它有两个字母),并且仅加载用户“ MattGilbert”,而不是“ TaylorSwift”?

这是我的代码:

import UIKit
import FirebaseDatabase
import Firebase
import SDWebImage
import ObjectMapper

class FollowUsersTableViewController: UIViewController {

    @IBOutlet var tableView: UITableView!

    private var viewIsHiddenObserver: NSKeyValueObservation?
    let searchController = UISearchController(searchResultsController: nil)
    var usersArray = [UserModel]()
    var filteredUsers = [UserModel]()
    var loggedInUser: User?
    //
    var databaseRef = Database.database().reference()
    //usikker på den koden over

    override func viewDidLoad() {

        super.viewDidLoad()

        //large title
        self.title = "Discover"
        if #available(iOS 11.0, *) {
            self.navigationController?.navigationBar.prefersLargeTitles = true
        } else {
            // Fallback on earlier versions
        }

        self.tableView?.delegate = self
        self.tableView?.dataSource = self
        searchController.searchResultsUpdater = self
        searchController.dimsBackgroundDuringPresentation = false
        self.searchController.delegate = self;

        definesPresentationContext = true
        tableView.tableHeaderView = searchController.searchBar

        //self.loadProfileData()

       //self.searchBar(searchController.searchBar, textDidChange: searchController.searchBar.text)
    }

    func searchUsers(text: String) {
        if text.count >= 2 {
            self.usersArray = [] //clear the array each time
            let endingText = text + "\u{f8ff}"
            databaseRef.child("profile").queryOrdered(byChild: "username")
                .queryStarting(atValue: text)
                .queryEnding(atValue: endingText)
                .observeSingleEvent(of: .value, with: { snapshot in

                    for child in snapshot.children {
                        let childSnap = child as! DataSnapshot
                        print(childSnap)
                        let userObj =  Mapper<UserModel>().map(JSONObject: childSnap.value!)
                        userObj?.uid = childSnap.key
                        if childSnap.key != self.loggedInUser?.uid { //ignore this user
                            self.usersArray.append(userObj!)

                        }
                    }
                    self.tableView.reloadData()
                })
        }
    } //may need an else statement here to clear the array when there is no text

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let dest = segue.destination as! UserProfileViewController
        let obj = sender as! UserModel
        let dict = ["uid": obj.uid!, "username": obj.username!, "photoURL": obj.photoURL, "bio": obj.bio]
        dest.selectedUser = dict as [String : Any]
    }
}

// MARK: - tableview methods
extension FollowUsersTableViewController: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return searchController.searchBar.text!.count >= 2 ? filteredUsers.count : 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! FollowTableViewCell

        let user = filteredUsers[indexPath.row]

        cell.title?.text = user.username
        if let url = URL(string: user.photoURL ?? "") {
            cell.userImage?.sd_setImage(with: url, placeholderImage: #imageLiteral(resourceName: "user_male"), options: .progressiveDownload, completed: nil)
            cell.userImage.sd_setIndicatorStyle(.gray)
            cell.userImage.sd_showActivityIndicatorView()
        }

        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.performSegue(withIdentifier: "user", sender: self.filteredUsers[indexPath.row])
    }
}

// MARK: - search methods
extension FollowUsersTableViewController:UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate {

    func searchBar(_ searchBar: UISearchBar,
                   textDidChange searchText: String) {

        self.searchUsers(text: searchText)
    }

    func updateSearchResults(for searchController: UISearchController) {
        searchController.searchResultsController?.view.isHidden = false
        filterContent(searchText: self.searchController.searchBar.text!)

        self.tableView.reloadData()
    }

    func filterContent(searchText:String){
        if searchText.count >= 2{
            self.filteredUsers = self.usersArray.filter{ user in
                return(user.username!.lowercased().contains(searchText.lowercased()))
            }
        }
    } 
}

0 个答案:

没有答案