TableView中带有JSON对象的搜索栏-Swift

时间:2018-11-14 06:49:02

标签: json swift

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UISearchDisplayDelegate{

@IBOutlet weak var recipeTable: UITableView!

@IBOutlet weak var searchbarValue: UISearchBar! 

// search functionality

var filteredAnswers: [JSON]?


func searchBarSearchButtonClicked(_ searchBar: UISearchBar){

    self.filteredAnswers?.removeAll()
    if (searchBar.text?.isEmpty)! {
        self.filteredAnswers = self.recipes     } else {
        if self.recipes.count > 0 {
            for i in 0...self.recipes.count - 1 {
                let answer = self.recipes[i] as [Dictionary<String, AnyObject>]
                if answer.title.range(of: searchBar.text!, options: .caseInsensitive) != nil {
                    self.filteredAnswers.append(answer)
                }
            }
        }
    }
    recipeTable.reloadData();
    recipeTable.reloadInputViews();
    searchBar.resignFirstResponder()
}





//end search parameters


// tableview functionionalitys
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return recipes.count

}


// tableview functionalities
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! RecipeTableViewCell

    cell.recipeLabel.text = recipes[indexPath.row].title
    //cell.textLabel?.text = recipe.title
    //cell.imageView?.image = recipe.imageUrl

    return cell

}


// structs for json
struct Root : Decodable {
    let count : Int
    let recipes : [Recipe]
}

struct Recipe : Decodable { // It's highly recommended to declare Recipe in singular form
    let recipeId : String
    let imageUrl, sourceUrl, f2fUrl : URL
    let title : String
    let publisher : String
    let socialRank : Double
    let page : Int?
    let ingredients : [String]?
}

//recipes is array of Recipes
var recipes = [Recipe]() // array of recipes

//unfiltered recipes to put into search
var filteredRecipes = [Recipe]()




fileprivate func getRecipes() {

    let jsonURL = "http://food2fork.com/api/search?key=264045e3ff7b84ee346eb20e1642d9d9"
        //.data(using: .utf8)!

    //let somedata = Data(jsonURL.utf8)

    guard let url = URL(string: jsonURL) else{return}

    URLSession.shared.dataTask(with: url) {(data, response , err) in
        if let response = response as? HTTPURLResponse, response.statusCode != 200 {
            print(response.statusCode)
            return
        }
        DispatchQueue.main.async {

            if let err = err{
                print("failed to get data from URL",err)
                return
            }
            guard let data = data  else{return}
            //print(String(data: data, encoding: .utf8))
            do {
                let decoder = JSONDecoder()
                decoder.keyDecodingStrategy = .convertFromSnakeCase
                let result = try decoder.decode(Root.self, from: data)
                self.recipes = result.recipes
                //print(result.recipes)
                self.recipeTable.reloadData()
            }catch let jsonERR {
                print("Failed to decode",jsonERR)
            }
        }

    }.resume()

}



override func viewDidLoad() {

    super.viewDidLoad()

    //search functionalities

     self.searchbarValue.delegate = self

    //call json object
    getRecipes()
  } 
}

我正在尝试实现一个搜索栏,该搜索栏从JSON对象获取配料,并在我的表格视图中显示包含这些配料的配方。我希望有一些最佳实践,并为此提供帮助。我尝试了几种不同的策略,但似乎都没有效果。

这是我尝试实现的最后一个,但是搜索功能出现错误。

  searchBarSearchButtonClicked中的

self.recipes.count无法分配值   类型为[[ViewController.Recipe]”的类型为“ [JSON]?

但是我也在-中断言失败-

  

[UISearchResultsTableView   _dequeueReusableCellWithIdentifier:forIndexPath:usingPresentationValues:]

我希望获得帮助,但同时也要寻求改善的最佳方法。谢谢。

1 个答案:

答案 0 :(得分:0)

首先,过滤配方的逻辑无法正常工作,并且效率非常低下。看来您是从完全不相关的源复制并粘贴了代码。

基本上,数据源数组的类型和过滤后的数组的类型必须相同,因此必须使用filteredRecipes而不是filteredAnswers

要过滤具有匹配成分的食谱,请使用filtercontains

func searchBarSearchButtonClicked(_ searchBar: UISearchBar){

    filteredRecipes.removeAll()
    if let searchText = searchBar.text, !searchText.isEmpty {
        self.filteredRecipes = self.recipes.filter { recipe in 
            guard let ingredients = recipe.ingredients else { return false }
            return ingredients.contains { $0.range(of: searchText, options: .caseInsensitive) != nil }
        }
    } else {
        self.filteredRecipes = self.recipes 
    } 

    recipeTable.reloadData();
    recipeTable.reloadInputViews();
    searchBar.resignFirstResponder()
}

实际上,该代码应该在委托方法中执行

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

而不是在searchBarSearchButtonClicked

而且-非常重要-您必须添加一个布尔属性来表示isSearching,并且在所有相关的数据源和委托方法中,如果{{1 }} 是真的。