UISearchController-搜索用户-tableview为空?火基/迅捷

时间:2018-10-29 21:05:07

标签: swift firebase tableview uisearchcontroller

我创建了一个SearchUserController来搜索用户,但是随后我开始添加它,以便在用户键入至少两个字符之前不显示表视图。出于某种奇怪的原因,当我输入两个单词时,表视图中什么也没有显示。

有人知道为什么吗?

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 >= 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
                    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 {

func updateSearchResults(for searchController: UISearchController) {
    searchController.searchResultsController?.view.isHidden = false
    filterContent(searchText: self.searchController.searchBar.text!)
    searchUsers(text: 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()))
        }
    }
}


 }

也值得一提:

  • 我不是使用情节提要创建searchcontroller,而是通过编程方式创建的。
  • 我说错了
  

firebase [MC]使缓存无效

在我在Firebase规则中添加.indexOn之前,现在它不再显示了-很奇怪。

0 个答案:

没有答案