質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.49%
TableView

TableView(UITableView)とは、リスト形式で表示するコントロールで、ほとんどのアプリに使用されています。画面を「行」に分けて管理し、一般的には各行をタップした際に詳細画面に移動します。

JSON

JSON(JavaScript Object Notation)は軽量なデータ記述言語の1つである。構文はJavaScriptをベースとしていますが、JavaScriptに限定されたものではなく、様々なソフトウェアやプログラミング言語間におけるデータの受け渡しが行えるように設計されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

配列

配列は、各データの要素(値または変数)が連続的に並べられたデータ構造です。各配列は添え字(INDEX)で識別されています。

Q&A

1回答

1100閲覧

【swift】tableからtableに画面遷移(JSONデータ)

mita0

総合スコア40

TableView

TableView(UITableView)とは、リスト形式で表示するコントロールで、ほとんどのアプリに使用されています。画面を「行」に分けて管理し、一般的には各行をタップした際に詳細画面に移動します。

JSON

JSON(JavaScript Object Notation)は軽量なデータ記述言語の1つである。構文はJavaScriptをベースとしていますが、JavaScriptに限定されたものではなく、様々なソフトウェアやプログラミング言語間におけるデータの受け渡しが行えるように設計されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

配列

配列は、各データの要素(値または変数)が連続的に並べられたデータ構造です。各配列は添え字(INDEX)で識別されています。

0グッド

0クリップ

投稿2019/08/30 06:41

編集2019/09/02 01:14

前提・実現したいこと

※初心者です

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. } */ }

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

takabosoft

2019/08/30 07:26

例えば"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, (省略) }
mita0

2019/08/30 07:36

コメントありがとうございます。 そうです。 説明不足で申し訳ございません。
takabosoft

2019/08/30 07:39

ThirdViewControllerのテーブルビューに何かしら表示すると思うのですが、上記のような連想配列を、テーブルにはどのように表示したいのでしょう??
mita0

2019/08/30 07:45

値番号(tapした箇所)で関連する情報が出したいです。
takabosoft

2019/08/30 07:54 編集

えーと、ViewControllerで"googletest"セルをタップして、それに関連づいた連想配列をThirdViewControllerまで持ってきたとして、ThirdViewControllerでは、テーブルビューの各セルにこの連想配列の内容をどういうルールで出すんでしょう?・・・という質問ですが伝わっていますかね。
mita0

2019/08/30 07:55

ThirdViewControllerでは順番に出したいです。 すいません。入門者のなのでうまく説明もできずで、、、
takabosoft

2019/08/30 08:04

プログラミングで覚えておいてほしいのは、「説明できないものは実装できない」、ことです。 なので、しっかりと説明できるようになってくださいね。 「順番に出したい」ではプログラムは書けません。 なにをどういうルールでどのように出すかを説明してください。 文章が難しければイメージ図(ラフ画)でも良いです。
takabosoft

2019/08/30 08:06

特に"owner"の値は更に連想配列になっていますので、それはどうするのか、といった仕様を決めてください。
mita0

2019/08/30 08:10

わかりました。 ありがとうございます。 気をつけます。 "googletest"をtapした場合”items”内にある"googletest関するデータをthirdviewのテーブル内でデータ順に出したいです。
mita0

2019/08/30 09:35

"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」内の情報」を順番に出したいです。
guest

回答1

0

追記・修正が山のようにされていて現状どうなっているのかよくわかりませんが、

通常はデータ用のStructを用意して、JSONではなく、
Structでデータを受け渡すようにするべきだと思います。

データが
id: 0,
name: 太郎,
pets:
(id:0, type: 犬, name: コロ, sex: 1),
(id:1, type: 猫, name: ミケ, sex: 0)
...などであれば、 一例までに

Swift

1Struct PetOwner { 2 id: Int 3 name: String 4 pets: [Pet] 5} 6 7Struct Pet { 8 id: Int 9 type: String 10 name: String 11 sex: Int // 0: 女性, 1:男性 を想定 12} 13 14 15class TableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 16 17 // ~~ 間省略 ~~ 18 var petOwners : [PetOwner] = [] 19 20 override func viewDidLoad() { 21 // ここでJSONからpetOwnersにデータを流し込む(別クラスで用意してもいいですが、、、) 22 } 23 24 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 25 if segue.identifier == "showPets" { // Identifierは適当です 26 let nextView = segue.destination as! PetsTableViewController 27 nextView.pets = petOwners[indexPath.row].pets // 選択されたrow番号のpetOwner.petsを次のviewに送っている 28 } 29 } 30 31 // ~~ その他省略 ~~ 32} 33 34class PetsTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 35 36 // ~~ 間省略 ~~ 37 var pets : [Pet] = [] 38 39 override func viewDidLoad() { 40 print("pets:", pets) 41 // これで前のviewからペットのリストを受け取れてるか確認できます。 42 } 43 44 // ~~ その他省略 ~~ 45}

同様に、データ構造に合わせて、Structを作り
Structを渡すようにしてみてくださいね。

投稿2019/09/01 23:45

hameji

総合スコア1380

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

mita0

2019/09/02 01:09 編集

ありがとうございます。 データ構造について承知しました。 今回は私情になるんですが、どうしてもJSONのデータを渡して、配列のデータを出せるようにしないといけないんです、、、 コードの修正に関しては質問欄にある通りで修正行っていません。 私の説明不足による説明の追記になります。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.49%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問