搜索其他用户,如果searchController为空,则返回0,这给我一个错误吗?

时间:2018-10-02 15:12:11

标签: swift xcode uitableview firebase uisearchcontroller

我正在尝试解决这个问题。我制作了一个以Firebase为后端的应用程序,并即时构建了一个搜索ViewController来搜索该应用程序上的其他用户。

很显然,我希望表视图为空,直到用户开始搜索为止(因此应用程序在用户甚至没有开始输入之前就先加载了应用程序上的每个用户)。

但是当我在numberOfRowsInSection返回0时,如果searchController为空,则会出现此错误:

'attempt to insert row 0 into section 0, but there are only 0 rows in section 0 after the update

这是我在ViewController中的代码:

class FollowUsersTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate ,UISearchResultsUpdating, UISearchControllerDelegate{





@IBOutlet var tableView: UITableView!

func updateSearchResults(for searchController: UISearchController) {

    searchController.searchResultsController?.view.isHidden = false
    filterContent(searchText: self.searchController.searchBar.text!)
    self.tableView.reloadData()


}
private var viewIsHiddenObserver: NSKeyValueObservation?
let searchController = UISearchController(searchResultsController: nil)
var usersArray = [NSDictionary?]()
var filteredUsers = [NSDictionary?]()
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

    databaseRef.child("profile").queryOrdered(byChild: "username").observe(.childAdded, with: { (snapshot) in


        let key = snapshot.key
        let snapshot = snapshot.value as? NSDictionary
        snapshot?.setValue(key, forKey: "uid")

        if(key == self.loggedInUser?.uid) {
            print("Same as logged in user, so don't show!")
        } else {
            self.usersArray.append(snapshot)
            //insert the rows
            self.tableView.beginUpdates()
            self.tableView.insertRows(at: [IndexPath(row:self.usersArray.count-1,section:0)], with: UITableViewRowAnimation.automatic)
            self.tableView.endUpdates()
        }


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

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem


}

// MARK: - Table view data source

func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {



    // here im trying to return 0

    if searchController.isActive && searchController.searchBar.text != ""{
        return filteredUsers.count
    }




        return 0



}


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




    let user : NSDictionary?

    if searchController.isActive && searchController.searchBar.text != ""{

        user = filteredUsers[indexPath.row]
    }
    else
    {
        user = self.usersArray[indexPath.row]
    }

    cell.title?.text = user?["username"] as? String
    let url = URL(string: user?["photoURL"] as! String)!
    cell.userImage?.sd_setImage(with: url, placeholderImage: #imageLiteral(resourceName: "user_male"), options: .progressiveDownload, completed: nil)


    return cell
}

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

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let arr = self.searchController.isActive ? self.filteredUsers : self.usersArray
    self.performSegue(withIdentifier: "user", sender: arr[indexPath.row])
}

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

func filterContent(searchText:String)
{
    if searchText != ""{
        self.filteredUsers = self.usersArray.filter{ user in

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

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


        }
    }




}

我了解到有人在此出现此错误,并尝试实现:

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

这没用,它仍然给我错误。

有人找到解决方案吗?真的很棒,这个问题已经困扰了我一周。

0 个答案:

没有答案