简体   繁体   中英

Swift 2 - REST service and TableView filtered by a search bar

Hi I'm trying to implement a table view that searches/filters the data by a search bar. The idea is that for every character (or group of characters) that the user inserts in the search bar, the app sends a REST query to the server and the data is shown in the table view.

The problem is that the table doesn't refresh. For example if I insert "Marco" in the search bar, the table shows the data only after I insert a new character. It seems that the table views are synchronized one step behind.

My implementation is this, what is wrong?

class MyViewController: UITableViewController, UISearchBarDelegate {

var queue = NSOperationQueue()

var scrollId: String?
var data: Array<String> = []

override func viewDidLoad()
{
    super.viewDidLoad()
    queue.maxConcurrentOperationCount = 1        
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()        
}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.data.count        
}


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

    let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")

    let f = self.data[indexPath.row]
    cell.textLabel?.text = f

    return cell
}


override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

    if (indexPath.row != data.count - 1) {
        return
    }
    if (scrollId != nil) {
       getMoreDataAndRefresh(self.scrollId!)
    }
}      

internal func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    getFoodAndRefreshTable(searchText);
}




///////////////////////////////////

private func getMoreDataAndRefresh(scrollId:String) -> Void {

    let downloadFood = NSBlockOperation(block: {

        let wrap:Wrap = self.getFoodAndAwaitTermination(nil, scrollId: self.scrollId)
        if wrap.error != nil {                
            print("Opsss!: \(wrap.error)")
            return
        }

        NSOperationQueue.mainQueue().addOperationWithBlock({
            if (wrap.data != nil) {
                self.data.appendContentsOf(wrap.data!)                    
                self.tableView.reloadData()
            }
        })

    })
    queue.addOperation(downloadFood)
}


private func getFoodAndRefreshTable(searchText:String?) -> Void {
    let downloadFood = NSBlockOperation(block: {

        let wrap:Wrap = self.getFoodAndAwaitTermination(searchText, scrollId: nil)

        if wrap.error != nil {            
            print("Opsss!: \(wrap.error)")
            return
        }

        NSOperationQueue.mainQueue().addOperationWithBlock({
            if self.scrollId != nil {
                dataAccess.clearRequest(self.scrollId!)
            }
            self.scrollId = wrap.scrollId;
            if (wrap.data != nil) {

                self.data.removeAll()
                self.data.appendContentsOf(wrap.data!)
            }

            self.tableView.reloadData()                
        })            
    })        
    queue.addOperation(downloadFood)       
}


private func getFoodAndAwaitTermination(text:String?, scrollId:String?) -> Wrap {

    let semaphore = dispatch_semaphore_create(0);
    var s:String?
    var r:Array<String> = []
    var e:String?

    dataAccess.getAllFood(text, scrollId : scrollId, pageSize: 20) { (result, scrollId, error) in
        if (error != nil ) {                
            e = error!
        } else {                
            s = scrollId!
            r.appendContentsOf(result!)                
        }         
        dispatch_semaphore_signal(semaphore);
    }

    let timeout = dispatch_time(DISPATCH_TIME_NOW, 20000000000)               
    let res = dispatch_semaphore_wait(semaphore, timeout);        
    return Wrap(food: r, scrollId: s, error: e)       

}


class Wrap {
    var data:Array<String>?
    var scrollId:String?
    var error:String?


    init(food:Array<String>?, scrollId:String?, error:String?) {
        self.data = data
        self.scrollId = scrollId
        self.error = error
    }
}

The main issue you are facing is because, You have implemented textDidChagned delegate of search bar use below code instead and it will work for you.

Cheers!!

func searchBar(searchBar: UISearchBar, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {

        var textFieldString : String = ""
        if let searchText = searchBar.text {
            textFieldString = searchText+text
        } else {
            textFieldString = text
        }
        getFoodAndRefreshTable(textFieldString)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM