前提・実現したいこと
※初心者です
jsonデータ(items)を画面遷移で渡したいです。 それにともなってやりたいことは以下の通りです。 ①メンバ変数に定義(配列のデータを配列に格納したい) ②JSONデータの受け渡し(tableviewのTapした箇所) Googleと検索した際にforの中で「items」をループで取り出しています。 「hosts」「googletest」など順にtableに出力されます。 tableで「hosts」をタップした時に「hosts内の情報」、「googletest」をタップした時に「googeltest」内の情報」を順番に出したいです。 ※ JSONデータ https://api.github.com/search/repositories?q=%20Google (配列の中に連想配列があります) 下記、JSON + searchBar.text!からの値になります。 "total_count": 553223, "incomplete_results": false, "items": [ { "id": 21481439, "node_id": "MDEwOlJlcG9zaXRvcnkyMTQ4MTQzOQ==", "name": "hosts", "full_name": "kelthuzadx/hosts", "private": false, "owner": { "login": "kelthuzadx", "id": 5010047, "node_id": "MDQ6VXNlcjUwMTAwNDc=", "avatar_url": "https://avatars0.githubusercontent.com/u/5010047?v=4", "gravatar_id": "", "url": "https://api.github.com/users/kelthuzadx", "html_url": "https://github.com/kelthuzadx", "followers_url": "https://api.github.com/users/kelthuzadx/followers", "following_url": "https://api.github.com/users/kelthuzadx/following{/other_user}", "gists_url": "https://api.github.com/users/kelthuzadx/gists{/gist_id}", "starred_url": "https://api.github.com/users/kelthuzadx/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/kelthuzadx/subscriptions", "organizations_url": "https://api.github.com/users/kelthuzadx/orgs", "repos_url": "https://api.github.com/users/kelthuzadx/repos", "events_url": "https://api.github.com/users/kelthuzadx/events{/privacy}", "received_events_url": "https://api.github.com/users/kelthuzadx/received_events", "type": "User", "site_admin": false }, "html_url": "https://github.com/kelthuzadx/hosts", "description": ":statue_of_liberty:最新可用的google hosts文件。国内镜像:",
行ったこと
画面遷移は実装確認済みです。
該当のソースコード
import UIKit class ViewController: UIViewController, UISearchBarDelegate, URLSessionDelegate, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var names: [String] = [] //★メンバ変数を定義 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.names.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel!.text = self.names[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("(indexPath.row)選択") tableView.deselectRow(at: indexPath, animated: true) performSegue(withIdentifier: "toNextViewController", sender: nil) } // ①セグエ実行前処理 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // ②Segueの識別子確認 if segue.identifier == "toNextViewController" { // ③遷移先ViewCntrollerの取得 let nextView = segue.destination as! ThirdViewController //④test print("データ渡し確認") ④値の設定 //★データを受け渡し(tableviewのTapした箇所) } } override func viewDidLoad() { searchBar.delegate = self searchBar.showsCancelButton = true super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBOutlet weak var searchBar: UISearchBar! func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { print("Sesrch") print(searchBar.text!) names.removeAll() get() self.view.endEditing(true) } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { print("Cansell") } func get() { guard let url = URL(string: "https://api.github.com/search/repositories?q=(searchBar.text!)") else { print("no such fite") return } let session = URLSession.shared let task = session.dataTask(with: url, completionHandler: {(data, response, error) in let str = String(data: data!, encoding: String.Encoding.utf8) do { let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) let jsons = json as! Dictionary<String, Any>;() let items = jsons["items"] as! Array<Any>;() for value in items { let value = value as! Dictionary<String, Any>;() self.names.append(value["name"] as! String) //let names = names as! Dictionary<String, Any>;() // self.hosts.append(names["hosts"]as! String) } DispatchQueue.main.async { self.tableView.reloadData() } print(self.names) } catch { print(error) } }) task.resume() } }
import UIKit class ThirdViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var hosts: [String] = [] func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.hosts.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel!.text = hosts[indexPath.row] return cell } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func back() { self.navigationController?.popToRootViewController(animated: true) } @IBAction func byPerformSegue(_ sender: Any) { self.performSegue(withIdentifier: "toSegueViewController", sender: nil) } //self.navigationController?.popViewController(animated: true) /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }