从swift3中的json搜索检索到的数据

时间:2018-02-21 14:03:32

标签: swift uisearchbar

我从swift3中的服务URL检索数据并在tableview中显示。我试图搜索名称,它显示过滤的名称,但另一个单元格没有更新。请查看我的以下代码。

class MyViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate {

    @IBOutlet weak var tableView: UITableView!

    @IBOutlet weak var searchBar: UISearchBar!
    var filteredArray = [String]()
    var shouldShowSearchResults = false
    var nameArray = [String]()
    var emailArray = [String]()

  var tableData = [String]()
    override func viewDidLoad() {
        super.viewDidLoad()
        downloadData()
   createSearchBar()
        // Do any additional setup after loading the view.
    }
    func createSearchBar(){
        searchBar.showsCancelButton = false
        searchBar.placeholder = "Enter your search"
        searchBar.delegate = self
        self.navigationItem.titleView = searchBar
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        tableData = nameArray
        if shouldShowSearchResults
        {
            return filteredArray.count
        }
        else
        {
            return tableData.count
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:mycell! = tableView.dequeueReusableCell(withIdentifier: "cell") as! mycell
        if shouldShowSearchResults
        {
            cell.name.text = filteredArray[indexPath.row]
            cell.email.text = emailArray[indexPath.row]
            return cell
        }
        else
        {
            cell.name.text = tableData[indexPath.row]
            cell.email.text = emailArray[indexPath.row]

            return cell

        }
    }
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        searchBar.endEditing(true)
    }
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        shouldShowSearchResults = true
        searchBar.endEditing(true)
        self.tableView.reloadData()
    }
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        filteredArray = tableData.filter({
            (names:String) -> Bool in
            return names.lowercased().range(of: searchText.lowercased()) != nil
        })
        if searchText != ""
        {
            shouldShowSearchResults = true
            self.tableView.reloadData()
        }
        else
        {
            shouldShowSearchResults = false
            self.tableView.reloadData()
        }
    }
    func downloadData()
    {
        let url = URL(string: "http://www.json-generator.com/api/json/get/crdvbKvLoy?indent=2")!

        var request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 10000)


        URLSession.shared.dataTask(with: request) { (data, response, error) in
            if error != nil {
                print(error!)
                return
            }

            do {
                if let jsonData = try JSONSerialization.jsonObject(with:data!, options: []) as? [[String:AnyObject]] {
                    print(jsonData)
                    //    Utility.SharedInstance.dict_UserDetails3 = jsonData as AnyObject

                    for item in jsonData {

                        if let name = item["Name"] as? AnyObject {
                            self.nameArray.append(name as! String)

                        }

                        if let email = item["Email"] as? AnyObject{
                            self.emailArray.append(email as! String)
                        }

                        DispatchQueue.main.async {
                            self.tableView.reloadData()
                        }
                    }
                }
            } catch let error as NSError {
                print(error)
            }
            }.resume()
    }

}


output:
search___________
Name      Email
----------------
Wasim     wasim@gmail.com
Dravid    dravid@gmail.com
Kohli     virat@gmail.com
Kallis    Jaques@gmail.com


I entered in search text as K
-----------------------------
search_____K______
Name      Email
----------------
Kohli     wasim@gmail.com
Kallis    dravid@gmail.com

在此搜索工作中,但电子邮件字段未更新。请检查一次。我尝试了更多的样品,但没有解决。请检查一次,我做了哪些改变来解决这个问题。

1 个答案:

答案 0 :(得分:0)

您过滤名称数组但不过滤电子邮件地址数组。因此索引不匹配。

最佳解决方案是不分离相关数据。正确地构造它。

struct Person {
   var name: String
   var email: String
}

var people: [Person]?
var filteredResults: [Person]?

对于同时拥有名称和电子邮件的人使用结构,您可以更轻松地过滤此数组,并且数据不会不同步。