我在键入时UISearchController不检索用户

时间:2016-02-01 17:23:01

标签: ios swift parsing uisearchcontroller

我想使用swift和Parse从PFUser类中搜索名字和姓氏来关注和取消关注用户。我使用了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()
}

2 个答案:

答案 0 :(得分:0)

在您同时书写时使用以下方法进行搜索

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

答案 1 :(得分:0)

我的建议是使用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)

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

以下是关于如何使用Predicates的Parse指南的链接 - 我强烈建议使用它们。 https://www.parse.com/docs/ios/guide#queries-specifying-constraints-with-nspredicate

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