如何在我的searchcontroller中使用queryStartingAtValue搜索用户?

时间:2018-10-24 17:18:30

标签: swift firebase firebase-realtime-database uisearchcontroller

我之前曾问过一个有关以最经济高效的方式搜索用户(而不必加载整个数据库中的每个用户)的问题。

问题之前我的代码是

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()
}

func loadProfileData() {
    databaseRef.child("profile").queryOrdered(byChild: "username").observe(.childAdded, with: { (snapshot) in
        print(snapshot)
        let userObj =  Mapper<UserModel>().map(JSONObject: snapshot.value!)
        userObj?.uid = snapshot.key

        guard snapshot.key != self.loggedInUser?.uid else { return }

        self.usersArray.append(userObj!)
    })
}

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 {

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()))
        }
    }
   }
  }

但是随后用户“ maxwell”回复了我,并建议像这样使用queryStartingAtValue:

func searchQueryUsers(text: String, completion: @escaping (_ userNames: [String]) -> Void) {

    var userNames: [String] = []

    databaseRef.child("profile").queryOrdered(byChild: "username").queryStarting(atValue: text).observeSingleEvent(of: .value, with: { snapshot in

        for item in snapshot.children {

            guard let item = item as? DataSnapshot else {
                break
            }

            //"name" is a key for name in FirebaseDatabese model
            if let dict = item.value as? [String: Any], let name = dict["name"] as? String {
                userNames.append(name)
            }
        }

        completion(userNames)
    })
}

如何使用已经存在的Mapper<UserModel>().map(JSONObject)代码来实现这一点?我尝试实现他的代码,却找不到真正有效的方法,而且似乎无法进入maxwell,所以有人可以帮助我吗?

我应该在maxwells代码中使用searchController.searchBar.text作为“文本”吗?

谢谢

已更新杰伊:

 class FollowUsersTableViewController: UIViewController, 
 UISearchBarDelegate {

@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 > 0 {
        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
                    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]
}

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

    self.searchUsers(text: searchText)
}




 }

2 个答案:

答案 0 :(得分:2)

问题中的代码几乎是正确的,只需对其进行调整以确保枚举var是快照,然后将其与Mapper一起使用。

当用户输入用户名时,每次按键都会递归调用它;因此,如果他们在Leroy中键入,则首先键入L,此代码将检索用户名值以“ L”开头的所有节点。然后用户输入“ e”,使其变为“ Le”等。

func searchUsers(text: String) {
    if text.count > 0 {
       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
               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

编辑:

OP请求的代码,用于通过searchBar和if语句来处理搜索,以防止在没有文本的情况下进行搜索。这是调用上面的searchUsers函数的委托方法

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

    self.searchUsers(text: searchText)
}

编辑:

OP希望看到我的viewDidLoad函数原样令人兴奋,所以就在这里。

class ViewController: UIViewController, UISearchBarDelegate 
    override func viewDidLoad() {
       super.viewDidLoad()

       // Do any additional setup after loading the view.
    }

答案 1 :(得分:1)

我将其添加为单独的答案,因为OP还有其他间接相关的问题:

这是我的整个代码库

class ViewController: UIViewController, UISearchBarDelegate {
    @IBOutlet var searchBarOutlet: [UISearchBar]!
     override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.
        self.searchBar.delegate = self
     }

    var userNamesArray = [String]()
    func searchBar(_ searchBar: UISearchBar,
                   textDidChange searchText: String) {

        self.searchUsers(text: searchText)
    }

    func searchUsers(text: String) {
        self.userNamesArray = []
        if text.count > 0 {
            let ending = text + "\u{f8ff}"
            let databaseRef = self.ref.child("users")
            databaseRef.queryOrdered(byChild: "Name")
                .queryStarting(atValue: text)
                .queryEnding(atValue: ending)
                .observeSingleEvent(of: .value, with: { snapshot in
                    for child in snapshot.children {
                        let childSnap = child as! DataSnapshot
                        let userName = childSnap.childSnapshot(forPath: "Name").value as! String
                        self.userNamesArray.append(userName)
                    }
                    print(self.userNamesArray) //here you would call tableView.reloadData()
                })
        }
    }
}

仅此一步,而不是将self.ref分配给我的Firebase。我的结构是:

users
  uid_0
    name: "Frank"
  uid_1
    name: "Fred"
  uid_2
    name: "Finay"

等当我在搜索字段'F'中键入时,得到以下输出

["Frank", "Fred", "Friday"]

然后当我输入'Fr'时,我得到以下输出

["Frank", "Fred"]

如您所见,它可以工作。如果在您的情况下不起作用,则可能未正确连接tableView或与搜索无关的其他问题。

现在,我不使用tableView,而只是将名称字符串打印到控制台,因此您需要在我的print语句的地方执行tableView.reloadData()。