前提・実現したいこと
gitのjsonデータ(URL + SearchBar)をTableViewで表示したいです。
json = https://api.github.com/search/repositories?q="searchBar.text!"
(URL:https://api.github.com/search/repositories?q=Google)
わからない箇所
①tableView.reloadData()の場所
②DispatchQueue.main.async {}の場所と入力内容
③その他に必要なコードあればそちらも教えてください。
該当のソースコード
import UIKit class ViewController: UIViewController, UISearchBarDelegate, URLSessionDelegate, UITableViewDelegate, UITableViewDataSource { //tableviewのcellの数 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.names.count } //cellの要素を func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "tableView", for: indexPath) cell.textLabel!.text = self.names[indexPath.row] return cell } override func viewDidLoad() { super.viewDidLoad() searchBar.delegate = self searchBar.showsCancelButton = true // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var tableView: UITableView! var names: [String] = [] func searchBarSearchButtonClicked(_ searchBar:UISearchBar) { print("検索") print(searchBar.text!) get() // tableView.reloadData() //ui操作 } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { print("キャンセル") tableView.reloadData() } //アドレスデータを扱うURLクラス func get() { guard let url = URL(string: "https://api.github.com/search/repositories?q=(searchBar.text!)") else { print("no such file") return } //インスタンスの初期化 let session = URLSession.shared //ダウンロード処理が完了した時に戻されるタップル//非同期(mainじゃない) let task = session.dataTask(with: url, completionHandler: {(data, response, error) in let str = String(data: data!, encoding: String.Encoding.utf8) //print(str) do { //jsonをパースする(urlのjsonデータが全て入ってる) let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) let jsons = json as! Dictionary<String, Any>;() ////arrayを定義する let array = jsons["items"] as! Array<Any>;() //arrayを表示する() //print(array[0]) //let dictionarys = dictionary["id"] //print(dictionarys as Any) for value in array { let value = value as! Dictionary<String, Any>;() //Dictionaryに変換 //Dictionaryに変換後取り出す値の型を変換する //let values = value["name"] as! String self.names.append(value["name"] as! String) //print(values) // print(values) } print(self.names) } catch{ print(error) } self.tableView.reloadData() }) //taskを動かす task.resume() DispatchQueue.main.async { self.tableView } } }
発生している問題・エラーメッセージ
現在printで表示できているが、tableviewでは表示ができていない
回答1件
あなたの回答
tips
プレビュー