UISearchController 在我输入时不检索用户

UISearchController does not retrieve the user when I am typing

我想使用 swift 和 Parse 从 PFUser class 搜索名字和姓氏以关注和取消关注用户。我使用了 UISearchController,但它在我输入时不检索用户。当我按下回车键时,它只是检索了用户。 另一个问题是,当我搜索用户时,它只检索到名字而不是姓氏。例如,当我搜索 Sara John 时,它会检索到 Sara John 和 Sara March。然而,当我输入 M 时,它也检索到了 Sara March。问题是名字和姓氏一起没有被检索到!我该如何解决?

这是我的代码,我不知道我做错了什么,请帮忙。

  func loadSearchUsers(searchString: String) {


    let firstName = searchString
    let lastName = searchString

    let firstNameQuery:PFQuery = PFUser.query()!
    firstNameQuery.whereKey("first_name", matchesRegex: "(?i)\(firstName)")

    let lastNameQuery:PFQuery = PFUser.query()!
    lastNameQuery.whereKey("last_name", matchesRegex: "(?i)\(lastName)")

    let query = PFQuery.orQueryWithSubqueries([firstNameQuery, lastNameQuery])

    self.searchActive = true

    query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
       //1
        if let users = objects {

        if (error != nil)
        {
            let myAlert = UIAlertController(title:"Error", message:error?.localizedDescription, preferredStyle:UIAlertControllerStyle.Alert)
            let okAction = UIAlertAction (title: "OK", style: UIAlertActionStyle.Default, handler: nil)
            myAlert.addAction(okAction)
            self.presentViewController(myAlert, animated: true, completion: nil)

            return
        }
            self.searchUsers.removeAll(keepCapacity: false)
            self.userIds.removeAll(keepCapacity: false)
            self.isFollowing.removeAll(keepCapacity: false)
           //2
            for object in users {
               //3
                if let user = object as? PFUser {
                //4
                if user.objectId! != PFUser.currentUser()?.objectId {

                    self.searchUsers.append(user)

                    self.userIds.append(user.objectId!)
                    self.tableView.reloadData()

                    let query = PFQuery(className: "followers")
                    query.whereKey("followFrom", equalTo: PFUser.currentUser()!.objectId!)
                    query.whereKey("followTo", equalTo: user.objectId!)
                    query.whereKey("status", equalTo:"followed")

                    query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in

                        if let objects = objects {

                            if objects.count > 0 {

                                self.isFollowing[user.objectId!] = true

                            } else {

                                self.isFollowing[user.objectId!] = false

                            }
                        }

                        if self.isFollowing.count == self.userIds.count {
                            self.tableView.reloadData()
                            self.searchActive = false
                           }

                        })

            }
        }}
      }
    }
}

// MARK: - Search Bar Delegate Methods

func searchBarSearchButtonClicked(searchBar: UISearchBar) {

    let searchString: String = searchBar.text!.lowercaseString

        // Force search if user pushes button
    if (searchString != "") {
        loadSearchUsers(searchString)
    }else
    {loadSearchUsers("")}

    self.userSearchController.resignFirstResponder()
}

func searchBarCancelButtonClicked(searchBar: UISearchBar) {


    searchActive = false
    searchBar.text = ""
    self.resultsController.tableView.reloadData()
        }

   func updateSearchResultsForSearchController(searchController:   UISearchController) {
   let searchString = String()
            if       searchString.lowercaseString.containsString(self.userSearchController.searchBar.text!.lowercaseString) {
           if (searchString != "" && !self.searchActive) {
            loadSearchUsers(searchString)
           }
     //Updates the results tableview
      self.resultsController.tableView.reloadData()

 }
}
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    searchActive = true
    self.resultsController.tableView.reloadData()
}

边写边用下面的方法搜索

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

我的建议是通过 a] 使用 NSPredicate 和 b] 合并为 1 个查询来简化您的搜索查询。

// Pseudo code - you will need to pad this out with all the Parse fripperies
let searchKey = "Sara"
let pre = NSPredicate(format: "first_name CONTAINS %@ OR last_name CONTAINS %@", argumentArray: [search_key, search_key])
let qry = PFQuery(className: "User", predicate: pre)

您需要调整此代码以适应您调用查询的方式 - 在后台或针对固定的本地数据。但我认为这会对你有所帮助。

这里是关于如何使用谓词的 Parse 指南的 link - 我强烈推荐使用它们。 https://www.parse.com/docs/ios/guide#queries-specifying-constraints-with-nspredicate

记住 - 解析查询区分大小写。 这意味着如果您的存储值 = "Sara" 那么搜索 "sara" 将失败。通常最好添加一个包含小写文本值的隐藏列,然后使用该列进行搜索。