Group Group Group Group Group Group Group Group Group

Json data url Search Bar

func fetchArticles(){
    let urlRequest = URLRequest(url: URL(string: "http://jjj.com/j.json")!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 20)
    
    let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in
        
        if error != nil {
            print(error as Any)
            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["title"] as? String, let author = articleFromJson["author"] as?
                        String, let desc = articleFromJson["description"] as?
                        String, let url = articleFromJson["url"] as?
                        String, let urlToImage = articleFromJson["urlToImage"]
                        
                        as? String {
                        
                        article.author = author
                        article.desc = desc
                        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.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) {

Can you share the appropriate search bar function.

thanks for help.

Hi @cuneyttr, have you tried out this tutorial using search controller, https://www.raywenderlich.com/472-uisearchcontroller-tutorial-getting-started ? It’s pretty useful to get a search bar going.

Best,
Gina

This topic was automatically closed after 166 days. New replies are no longer allowed.