使用UISearchController无法正常搜索

时间:2016-01-30 22:17:09

标签: ios swift uisearchcontroller

当我使用以下配置进行搜索时,我可以得到结果,但我有几个问题:

  1. 当我搜索一个人时,我可以使用打印命令在底部的输出区域中看到结果,但它不会显示在屏幕上。如果我删除一个单词,它会显示结果!例如,如果我输入迈克尔,则不会显示结果,但如果我在迈克尔单词末尾删除字母L,则会正确显示结果。
  2. 有时搜索栏会作为第一响应者,有时不会。我需要点击两次搜索。
  3. 如果我在搜索词之后键入空格,则应用程序崩溃为"致命错误:数组索引超出范围"错误。
  4. 我的代码如下:

       func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            if shouldShowSearchResults {
                return filteredArray.count
            }
            else {
                return homesearchResults.count
            }
        }
    
        func updateSearchResultsForSearchController(searchController: UISearchController) {
    
    
        filteredTableData.removeAll(keepCapacity: false)
    
        let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
    
        if searchController.searchBar.text?.characters.count > 2
    
        {
    
        goSearch(searchController.searchBar.text!)
    
        }
    
        let array = (homesearchResults as NSArray).filteredArrayUsingPredicate(searchPredicate)
    
    
        filteredArray = array as! [String]
    
    
    
        self.homeTableView.reloadData() }
    
        func configureSearchController() {
    
        searchController = UISearchController(searchResultsController: nil)
        searchController.searchResultsUpdater = self
        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Search"
        searchController.searchBar.delegate = self
        searchController.searchBar.sizeToFit()
    
        let textFieldInsideSearchBar = searchController.searchBar.valueForKey("searchField") as! UITextField
        textFieldInsideSearchBar.font = UIFont(name: "Bauhaus", size: 19)
    
    
       searchController.searchBar.setImage(UIImage(named: "searchicon"), forSearchBarIcon: UISearchBarIcon.Search, state: UIControlState.Normal);
    
    
        homeTableView.tableHeaderView = searchController.searchBar}
    
        func searchBarTextDidBeginEditing(searchBar: UISearchBar)  {
    
        searchController.searchBar.becomeFirstResponder()}
    
    
    func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
    
        print ("searchBarSearchButton Clicked")
    
        return true
    }
    
    
     func goSearch(searchWord: String)
    
    {
    
    
        homeSearchBar.resignFirstResponder()
    
    
        let myUrl = NSURL(string: "http://bla.net/home.php")
    
        let request = NSMutableURLRequest(URL:myUrl!);
        request.HTTPMethod = "POST";
    
        let defaults = NSUserDefaults.standardUserDefaults()
    
        let user_id = defaults.integerForKey("dbID") as Int
    
    
    
        let postString = "searchWord=\(searchWord)&userId=\(user_id)";
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
    
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
            data, response, error in
    
    
                do {
                    let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
    
                    self.homesearchResults.removeAll(keepCapacity: false)
                    self.homeimageResults.removeAll(keepCapacity: false)
                    self.homeidResults.removeAll(keepCapacity: false)
    
                    self.homeTableView.reloadData()
    
                    if let parseJSON = json {
    
                        print(parseJSON)
    
                        if let friends  = parseJSON["friends"] as? [AnyObject]
                        {
    
    
                            for friendObj in friends
                            {
                                let fullName = (friendObj["name"] as! AnyObject)
    
                                self.homesearchResults.append(fullName as! String)
    
    
    
    
                                let friendRequestImage = (friendObj["thumb"] as! AnyObject)
    
                                self.homeimageResults.append(friendRequestImage as! String)
    
    
                                let NotID = (friendObj["id"] as! AnyObject)
    
                                self.homeidResults.append(NotID as! String)
    
    
                            }
    
    
                            self.homeTableView.reloadData()
    
                        } else if(parseJSON["message"] != nil)
                        {
    
                            let errorMessage = parseJSON["message"] as? String
                            if(errorMessage != nil)
                            {
                                self.displayAlertMessage(errorMessage!)
                            }
                        }
                    }}
                catch {
                    print("json error: \(error)")
                }
    
        }
    
    
    
        task.resume()
    
    }
    

1 个答案:

答案 0 :(得分:0)

我相信你需要在dispatch_async调用中(在你的doSearch方法中)包装你的do / catch语句:

dispatch_async(dispatch_get_main_queue(), { () -> Void in
     do {
            let json = try NSJSONSerialization.JSONObjectWithData(data!,
    ....
})