使用UISearchController将JSON Multi Data过滤到Swift3

时间:2017-11-23 04:18:19

标签: json swift3 ios10

我的项目有问题。当我在json的tableview中过滤数据(名称和代码)并选择该数据时,内容(代码)数据与select的名称不同。如果编码较少,请帮忙吗?

这是JSON:

}
    "project": [
        {
            "name": "IT and Digital",
            "code": “001”,
        },
        {
            "name": "Business Solution",
            "code": “002”,
        }
}

我使用两个viewcontroller viewcontroller1显示项目名称列表,viewcontroller2显示项目详细信息(名称和代码)

var arrName = [String]()
var arrCode = [String]()
var filterMyProject = [String]()
var myIndexPro = 0
var myIndexFilterPro = 0
var isFilterPro = false

ViewController1

    let url = URL(string: apiServer)
    URLSession.shared.dataTask(with: url!) {(data, response, error) in
        if error != nil {
            return
        }else{
            guard data != nil else {return}
            do {
                arrName.removeAll()
                arrCode.removeAll()

                let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]

                if let itemProject = json?["project"] as? [[String: Any]] {
                    for items in itemProject {
                        let name = items["name"] as! String
                        let code = items["code"] as! String

                        arrName.append(name)
                        arrCode.append(code)
                    }
                }

                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }

            }catch{
                print(error)
            }
        }
    }.resume()


func updateSearchResults(for searchController: UISearchController) {
    filterMyProject = arrName.filter { (tproject: String) -> Bool in
        if tproject.lowercased().contains(self.searchController.searchBar.text!.lowercased()) {
            return true
        }else{
            return false
        }
    }

    resultsController.tableView.reloadData()
}



override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let indexPath = self.tableView.indexPathForSelectedRow
    let indexPath2 = resultsController.tableView.indexPathForSelectedRow
    if tableView == resultsController.tableView {
        isFilterPro = true
        myIndexFilterPro = (indexPath2?.row)!
    }else{
        isFilterPro = false
        myIndexPro = (indexPath?.row)!
    }
    performSegue(withIdentifier: "listprojectSegue", sender: nil)
}

ViewController2

override func viewDidLoad() {
        super.viewDidLoad()

        if isFilterPro == false {
            labelListProject.text = arrName[myIndexPro]
            labelCode.text = arrCode[myIndexPro]
            print("Code: " + code)
        }else{
            labelListProject.text = filterMyProject[myIndexFilterPro]
            labelCode.text = arrCode[myIndexFilterPro]
            print("Code Filter: " + code)
        }
    }

0 个答案:

没有答案