Swift搜索栏问题

时间:2015-08-03 23:56:10

标签: ios swift

我有一个表视图控制器,它从网站上抓取json数据,并将每个记录的值显示为一行。 TVC有一个搜索栏代表,允许您按名称搜索记录。一切正常,除非您单击已过滤的记录(即,您在搜索栏中输入搜索值并单击已过滤的列表),它会将您带到错误的记录。我不确定我做错了什么,但感谢任何帮助

import UIKit

class SearchTableViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate {

@IBOutlet weak var searchBar: UISearchBar!

var searchActive : Bool = false
var filtered:[String] = []
var filteredURLs:[String] = []
var filteredName:[String] = []

var TableData2:Array< String > = Array < String >()
var TableData2URLs:Array< String > = Array < String >()
var TableDataName:Array< String > = Array < String >()


var passedValue:String!

override func viewDidLoad() {
    super.viewDidLoad()

    self.title = "Search"
    get_data_from_url(passedValue)

    /* Setup delegates */
    tableView.delegate = self
    tableView.dataSource = self
    searchBar.delegate = self

}

// functions added for search bar
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 = TableData2.filter({ (text) -> Bool in
        let tmp: NSString = text
        let range = tmp.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)
        return range.location != NSNotFound
    })
    filteredURLs = TableData2URLs.filter({ (text) -> Bool in
        let tmp: NSString = text
        let range = tmp.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)
        return range.location != NSNotFound
    })
    filteredName = TableDataName.filter({ (text) -> Bool in
        let tmp: NSString = text
        let range = tmp.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)
        return range.location != NSNotFound
    })

    if(filtered.count == 0){
        searchActive = false;
    } else {
        searchActive = true;
    }
    self.tableView.reloadData()
}

// End search bar code

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

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if(searchActive) {
        return filtered.count
    } else {
    return TableData2.count
    }
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell

    if(searchActive){
        cell.textLabel?.text = filtered[indexPath.row]
    } else {
    cell.textLabel?.text = TableData2[indexPath.row]
    }
    return cell
}


func get_data_from_url(url:String)
{
    let httpMethod = "GET"
    let timeout = 15
    let url = NSURL(string: url)
    let urlRequest = NSMutableURLRequest(URL: url!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 15.0)
    let queue = NSOperationQueue()
    NSURLConnection.sendAsynchronousRequest(
        urlRequest,
        queue: queue,
        completionHandler: {(response: NSURLResponse!,
            data: NSData!,
            error: NSError!) in
            if data.length > 0 && error == nil{
                let json = NSString(data: data, encoding: NSASCIIStringEncoding)
                self.extract_json(json!)
            }else if data.length == 0 && error == nil{
                println("Nothing was downloaded")
            } else if error != nil{
                println("Error happened = \(error)")
            }
        }
    )
}

func extract_json(data:NSString)
{
    var parseError: NSError?
    let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!
    let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &parseError)
    if (parseError == nil)
    {
        if let countries_list = json as? NSArray
        {
            for (var i = 0; i < countries_list.count ; i++ )
            {
                if let country_obj = countries_list[i] as? NSDictionary
                {
                    if let country_name = country_obj["country"] as? String
                    {
                        if let country_code = country_obj["region"] as? String
                        {
                            if let namevalue = country_obj["name"] as? String {
                                TableData2.append(namevalue + ": " + country_name )
                                TableData2URLs.append("http://www.example.com/jsondetail.php?value=" + namevalue)
                                TableDataName.append(namevalue)
                            }

                        }
                    }
                }
            }
        }
    }
    do_table_refresh();
}


func do_table_refresh()
{
    dispatch_async(dispatch_get_main_queue(), {
        self.tableView.reloadData()
        return
    })
}


// Pass url details for Segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "showDetail" {
        let detailViewController = segue.destinationViewController  as! DetailViewController

        let myIndexPath = self.tableView.indexPathForSelectedRow()
        let row = myIndexPath?.row

        if(searchActive && row < filteredURLs.count){

            detailViewController.webSite = filteredURLs[row!]
            detailViewController.name = filteredName[row!]
            detailViewController.title = filteredName[row!]

            println("Filtered URL: " + filteredURLs[row!])
            println(row)
            println("Filtered Name: " + filteredName[row!])
            println(row)

        } else {

            detailViewController.webSite = TableData2URLs[row!]
            detailViewController.name = TableDataName[row!]
            detailViewController.title = TableDataName[row!]
            println("Table URL: " + TableData2URLs[row!])
            println(row)

        }






    }
}


}

1 个答案:

答案 0 :(得分:0)

您过度复杂并且没有正确使用对象,您应该创建一个封装所需数据的对象,以便该类的一个实例可以保存每个单元所需的所有数据。所以你的数据源是这些对象的数组,例如[国家],过滤国家的另一个。这形成了模型。您可能也想存储该数据,因此您可以序列化对象。我会从那开始然后看看它是怎么回事。您将所有内容分成6个不同的数组,每个结果集3个。它使一切变得更加复杂。

如果允许的话,那些可以帮助你的东西也是更简洁的方式,例如

func extract_json(data:NSString)
{
    var parseError: NSError?
    let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!
    let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &parseError)

    if (parseError == nil)
    {
        if let countries_list = json as? NSArray
       {
            for i in 0..<countries_list.count
            {
                if let country_obj = countries_list[i] as? NSDictionary,
                country_name = country_obj["country"] as? String,
                country_code = country_obj["region"] as? String,
                namevalue = country_obj["name"] as? String 
                {
                     TableData2.append(namevalue + ": " + country_name )
                     TableData2URLs.append("http://www.example.com/jsondetail.php?value=" + namevalue)
                     TableDataName.append(namevalue)
                }
            }
        }
    }

    do_table_refresh();
}

关于选择的问题。你确定网址都被正确过滤了吗?