前提・実現したいこと
※初心者です
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. } */ }
例えば"googletest"というセルをタップしたら、以下のような"googletest"に関わる連想配列をまるごと次の画面に持っていきたいのでしょうか?
{
"id": 39840932,
"node_id": "MDEwOlJlcG9zaXRvcnkzOTg0MDkzMg==",
"name": "googletest",
"full_name": "google/googletest",
"private": false,
"owner": {
"login": "google",
"id": 1342004,
"node_id": "MDEyOk9yZ2FuaXphdGlvbjEzNDIwMDQ=",
"avatar_url": "https://avatars1.githubusercontent.com/u/1342004?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/google",
"html_url": "https://github.com/google",
"followers_url": "https://api.github.com/users/google/followers",
"following_url": "https://api.github.com/users/google/following{/other_user}",
"gists_url": "https://api.github.com/users/google/gists{/gist_id}",
"starred_url": "https://api.github.com/users/google/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/google/subscriptions",
"organizations_url": "https://api.github.com/users/google/orgs",
"repos_url": "https://api.github.com/users/google/repos",
"events_url": "https://api.github.com/users/google/events{/privacy}",
"received_events_url": "https://api.github.com/users/google/received_events",
"type": "Organization",
"site_admin": false
},
"html_url": "https://github.com/google/googletest",
"description": "Googletest - Google Testing and Mocking Framework",
"fork": false,
(省略)
}
コメントありがとうございます。
そうです。
説明不足で申し訳ございません。
ThirdViewControllerのテーブルビューに何かしら表示すると思うのですが、上記のような連想配列を、テーブルにはどのように表示したいのでしょう??
値番号(tapした箇所)で関連する情報が出したいです。
えーと、ViewControllerで"googletest"セルをタップして、それに関連づいた連想配列をThirdViewControllerまで持ってきたとして、ThirdViewControllerでは、テーブルビューの各セルにこの連想配列の内容をどういうルールで出すんでしょう?・・・という質問ですが伝わっていますかね。
ThirdViewControllerでは順番に出したいです。
すいません。入門者のなのでうまく説明もできずで、、、
プログラミングで覚えておいてほしいのは、「説明できないものは実装できない」、ことです。
なので、しっかりと説明できるようになってくださいね。
「順番に出したい」ではプログラムは書けません。
なにをどういうルールでどのように出すかを説明してください。
文章が難しければイメージ図(ラフ画)でも良いです。
特に"owner"の値は更に連想配列になっていますので、それはどうするのか、といった仕様を決めてください。
わかりました。
ありがとうございます。
気をつけます。
"googletest"をtapした場合”items”内にある"googletest関するデータをthirdviewのテーブル内でデータ順に出したいです。
"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文件。国内镜像:",
追記
Googleと検索した際にforの中で「items」をループで取り出しています。
「hosts」「googletest」など順にtableに出力されます。
tableで「hosts」をタップした時に「hosts内の情報」、「googletest」をタップした時に「googeltest」内の情報」を順番に出したいです。