Как сделать поиск [UISearchBar] - PullRequest
0 голосов
/ 10 января 2019

Я хочу создать поиск, используя UISearchBar для значения массива JSON.

Основная задача - отсортировать ячейки по городам, которые будут записаны в строке поиска

Но мой код не работает Я пытался создать новый массив, но он также не работал Я частично повторил код с YouTube-канала видео-урока Васила Нунева для разбора json

@IBOutlet weak var tableview: UITableView!
@IBOutlet weak var searchBar: UISearchBar!

var articles: [Article]? = []


func fetchArticles(){
    let urlRequest = URLRequest(url: URL(string: "http://jjj.json")!)

    let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in

        if error != nil {
            print(error)
            return
        }

        self.articles = [Article]()
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]

            if let articlesFromJson = json["articles"] as? [[String : AnyObject]] {
                for articleFromJson in articlesFromJson {
                    let article = Article()
                    if let title = articleFromJson["user_name"] as? String,
                        let desc = articleFromJson["desk"] as? String,
                        let url = articleFromJson["number"] as? String,
                        let city = articleFromJson["city"] as? String,
                        let city2 = articleFromJson["city2"] as? String,
                        let author = articleFromJson["date"] as? String,

                        let urlToImage = articleFromJson["img"] as? String {

                        article.author = author
                        article.desc = desc
                        article.city = city
                        article.city2 = city2
                        article.headline = title
                        article.url = url
                        article.imageUrl = urlToImage
                    }
                    self.articles?.append(article)
                }
            }
            DispatchQueue.main.async {
                self.tableview.reloadData()
            }

        } catch let error {
            print(error)
        }


    }

    task.resume()

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "articleCell", for: indexPath) as! ArticleCell

    cell.title.text = self.articles?[indexPath.item].headline
    cell.desc.text = self.articles?[indexPath.item].desc
    cell.city.text = self.articles?[indexPath.item].city
    cell.city2.text = self.articles?[indexPath.item].city2
    cell.url.text = self.articles?[indexPath.item].url
    cell.author.text = self.articles?[indexPath.item].author
    cell.imgView.downloadImage(from: (self.articles?[indexPath.item].imageUrl!)!)

    return cell
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.articles?.count ?? 0
}

func searchBar(_ searchBar:UISearchBar,textDidChange indexPath: IndexPath, searchText: String) {

    articles = articles?[indexPath.item].filter({article -> Bool in
        guard let text = searchBar.text else { return false }
        return article.city.contains(text) })
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...