user5513630
user5513630

Reputation: 1699

Tableview search bar not showing any data and giving some error some times when i run

I am using swift 2.0 . And i have added search bar to table view. i have run 2 times, its worked well. But now in my code its showing error :

Cannot invoke 'filter' with an argument list of type '(@noescape (Element) throws -> Bool)'

When i try to run also not able to search my table view data ,

Here is my full code:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate

{

    var Table:NSArray = []

  @IBOutlet weak var searchBar: UISearchBar!
    var searchActive : Bool = false
     var filtered:[String] = []


    @IBOutlet weak var tableView: UITableView!   // UITable view declaration

    @IBOutlet weak var Resultcount: UILabel!     // count label

    let cellSpacingHeight: CGFloat = 5  // cell spacing from each cell in table view




    var filteredTableData = [String]()
    var resultSearchController = UISearchController()

    override func viewDidLoad() {


        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

       CallWebService() // call the json method


        // nib for custom cell (table view)
        let nib = UINib(nibName:"customCell", bundle: nil)
        tableView.registerNib(nib, forCellReuseIdentifier: "cell")


        searchBar.delegate = self

    }

    func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
        searchActive = true;
    }

    func searchBarTextDidEndEditing(searchBar: UISearchBar) {
        searchActive = false;
    }

    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
        searchActive = false;
    }

    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        searchActive = false;
    }

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

        filtered = Table.filter({ (text) -> Bool in
            let tmp: NSString = text as! NSString
            let range = tmp.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)
            return range.location != NSNotFound
        })
        if(filtered.count == 0){
            searchActive = false;
        } else {
            searchActive = true;
        }
        self.tableView.reloadData()
    }



    // every time app quit and run, switch will be in off state
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(true)
        NSUserDefaults.standardUserDefaults().setBool(false, forKey: "PremiumUser")

    }





    func CallWebService()
    {
        let UrlApi = "url"
        let Url = NSURL(string: UrlApi)
        let Session = NSURLSession.sharedSession()
        let Work = Session.dataTaskWithURL(Url!, completionHandler: { dataTask, response, error -> Void in
            if (error != nil)
            {
                print(error)
            }
            var datos:NSData = NSData(data: dataTask!)

            do {


                let JsonWithDatos:AnyObject! = try NSJSONSerialization.JSONObjectWithData(datos, options: NSJSONReadingOptions.MutableContainers) as! NSArray


                self.Table = JsonWithDatos as! NSArray


                dispatch_async(dispatch_get_main_queue()) {



                    if (self.Table.count>0)
                    {
                        self.Resultcount.text = "\(self.Table.count) Results"
                        self.tableView.reloadData()
                    }


                }
            }catch{
                print("Some error occured")
            }


        })

        Work.resume()
    }




    // number of sections
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
       return 1
    }
    // number of rows
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {



        if(searchActive) {
            return filtered.count
        }
       return self.Table.count
    }







        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {



        let cell:customCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! customCell 
            if(searchActive){
               cell.vendorName.text = filtered[indexPath.row]
            } else {
                cell.vendorName.text = Table[indexPath.row] as! String;
            }

            let item = self.Table[indexPath.row] as! [String : String]
             cell.vendorName.text = item["name"]
            cell.vendorAddress.text = item["address"]


        return cell 
    }




}

i am getting error in this method func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { in this line filtered = Table.filter({ (text) -> Bool in let tmp: NSString = text as! NSString let range = tmp.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch) return range.location != NSNotFound })

Why its work one time , that time also not able to do search in my table view. Now I am suddenly getting this error.

Upvotes: 0

Views: 328

Answers (2)

Talha Ghous
Talha Ghous

Reputation: 63

i have implemented search controller in table view i give you my function that filter the searched data and make an array with matching strings

func filterDestinations(searchString: String){
    self.filteredDestinations.removeAll()
    if(self.defaultarray.count > 0){
        for obj in self.sortedDest{
            if(obj.name!.rangeOfString(searchString, options: .CaseInsensitiveSearch, range: nil, locale: nil) != nil){
                self.filteredDestinations.append(obj)
            }
        }
    }    
}// ends filterDestinations

after that you just reload your table view and in function cellforrowatindex you check that if search controller is active than you give data from your filltered array otherwise use your default array. also you have to set numberofrows by check search controller is active or not. if its active then return the filltered array count otherwise return your default array count so your app wont crash .

Upvotes: 1

Tapani
Tapani

Reputation: 3231

Just remove the closure parameter and return value type. Also rangeOfString returns nil if the string was not found. And better to cast to Swift String not NSString. You are trying to assign NSArray (basically [AnyObject] to [String]. You have to do some mapping.

filtered = table.filter {
    let tmp = $0 as! String
    let range = tmp.rangeOfString(searchText, options: .CaseInsensitiveSearch)
    return range != nil
}.map { $0 as! String }

Upvotes: 0

Related Questions