使用Async webservice调用的搜索栏不反映tableview reloadData()

时间:2015-09-28 14:22:01

标签: ios swift2

我尝试在异步调用中加载搜索结果,因此搜索文本不会花费太多时间进入。

它适用于viewDidLoad但是当我在搜索栏文本上调用相同的方法时,它会通过重新加载数据但不反映在UI上。当我点击搜索栏的取消按钮时会反映出来。我需要在searchBar上输入的每个搜索文本上反映reloadData。

我试过以下代码:非常感谢任何帮助。

import Foundation
import UIKit

class NSOperations {

    lazy var downloadQueue:NSOperationQueue = {
        var queue = NSOperationQueue()
        queue.name = "Image Download queue"
        queue.maxConcurrentOperationCount = 1
        return queue
        }()

    lazy var filtrationQueue:NSOperationQueue = {
        var queue = NSOperationQueue()
        queue.name = "Search Filtration queue"
        queue.maxConcurrentOperationCount = 1
        return queue
        }()

}
class SearchResultController: UIViewController, UITableViewDataSource, UITableViewDelegate,UISearchDisplayDelegate,  UISearchBarDelegate
{
    @IBOutlet var searchBar: UISearchBar!
    @IBOutlet weak var contactsTableView: UITableView!

    var genericArr = [Generic]()
    var utility = Utility()
    var constants = Constants()
    var netUtil = NetworkUtil()
    var controllerUtil = ControllerUtil()
    var parser = Parsers()
    var searchString = ""
    var filteredTableData = [Generic]()
    var searchActive : Bool = false
    let pendingOperations:NSOperations = NSOperations()


    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.contactsTableView.delegate = self
        self.contactsTableView.dataSource = self
        self.searchBar.delegate = self

    }

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

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

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

        filteredTableData.removeAll(keepCapacity: false)
        self.filteredTableData = [Generic]()
        if searchText != ""
        {
             searchActive = true
             self.suspendAllOperations()
             self.search(searchText)
        }
        else
        {
            searchActive = false
        }
    }

    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
        searchActive = false
        self.searchBar.resignFirstResponder()
    }

    func tableView(tableView:UITableView, numberOfRowsInSection section:Int) -> Int {
        var count:Int = 0
        if self.searchActive == true {
            count = self.filteredTableData.count
        }
        else{
            count = self.genericArr.count
        }
        return count

    }

    func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell {
        let resultCell = self.contactsTableView.dequeueReusableCellWithIdentifier("ResultCell") as! ResultCell
        var result:Generic = Generic()
        if searchActive == true && self.filteredTableData.count > 0
        {
            result = self.filteredTableData[indexPath.row]
            resultCell.setResultCell(result)
        }
        else
        {
            result = self.genericArr[indexPath.row]
            resultCell.setResultCell(result)
        }
        return resultCell
    }

    func suspendAllOperations () {
        pendingOperations.downloadQueue.suspended = true
        pendingOperations.filtrationQueue.suspended = true
    }

    func resumeAllOperations () {
        pendingOperations.downloadQueue.suspended = false
        pendingOperations.filtrationQueue.suspended = false
    }

    func search(searchTxt: String){

        let searchUrl: String = "\(constants.SERVER_URL)\(constants.SEARCH_RESULT_URL)\(searchTxt.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)"
        pendingOperations.filtrationQueue.addOperationWithBlock({

        self.netUtil.callJSONData(searchUrl) {(dataDictionary) -> Void in

            self.errorStr = dataDictionary[self.constants.defaultsKeys.RESPONSE_ERROR] as! String
            let data: AnyObject? = dataDictionary[self.constants.defaultsKeys.RESPONSE_RESULT]

            if(self.errorStr.isEmpty || self.errorStr==""){

                if data != nil {

                    if let jsonNSData = data as? NSData
                    {
                        if let resultDict :NSDictionary = (try! NSJSONSerialization.JSONObjectWithData(jsonNSData, options:  NSJSONReadingOptions.MutableContainers)) as? NSDictionary{

                            self.loadData(resultDict)
                            print("count >> \(self.genericArr.count)")

                           dispatch_async(dispatch_get_main_queue()) {

                                self.contactsTableView.reloadData()
                           }

                        }
                    }

                }
                else{
                   // self.showError("something is wrong happened")
                }
            }
            else{
               // self.showError(self.errorStr)

            }
        }
       })
     }

    func loadData(resultDict : NSDictionary){
        let genArray:[Generic] = parser.getGenericArr(resultDict)
        if searchActive == true{
            self.filteredTableData = [Generic]()
            self.filteredTableData.appendContentsOf(genArray)
        }
        else{
            self.genericArr = [Generic]()
            self.genericArr.appendContentsOf(genArray)
        }
    }
    func callJSONData(urlStr: String, callback: ((data: Dictionary<String,AnyObject>) -> Void)!)
    {

        let url = NSURL(string: urlStr)!
        var dict = Dictionary<String,AnyObject>()
        var errorStr = ""

        if let data = NSData(contentsOfURL: url) {

                dict = Dictionary<String,AnyObject>()
                self.parser.getJSONResultDataDictionary(data) {(dataDictionary) -> Void in
                    errorStr = dataDictionary[self.constants.defaultsKeys.RESPONSE_ERROR] as! String
                    if(errorStr.isEmpty || errorStr==""){
                        if let dataDict = dataDictionary[self.constants.defaultsKeys.RESPONSE_RESULT] as? Dictionary<String,AnyObject>
                        {
                            dict = dataDict
                            dict[self.constants.defaultsKeys.RESPONSE_ERROR] = errorStr
                        }
                        else{
                            dict[self.constants.defaultsKeys.RESPONSE_ERROR] = errorStr
                        }
                    }
                    else
                    {
                        dict[self.constants.defaultsKeys.RESPONSE_ERROR] = errorStr
                    }
                }
         }
        else{
            dict = Dictionary<String,AnyObject>()
            dict[self.constants.defaultsKeys.RESPONSE_ERROR] = errorStr
        }
         callback(data:  dict)

    }

}

0 个答案:

没有答案