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

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

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

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

Git

Gitはオープンソースの分散バージョン管理システム(DVCS)です。

JSON

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

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

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

Q&A

解決済

1回答

1480閲覧

【swift】 TableViewが表示されない

mita0

総合スコア40

TableView

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

Git

Gitはオープンソースの分散バージョン管理システム(DVCS)です。

JSON

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

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

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

0グッド

0クリップ

投稿2019/08/23 04:20

編集2019/08/30 06:45

前提・実現したいこと

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では表示ができていない

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

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

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

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

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

pftyuk

2019/08/23 04:25

tableViewのdataSourceの設定はストーリーボードでされているのでしょうか?
mita0

2019/08/23 04:28

はい、ストーリーボードでやりました。
guest

回答1

0

ベストアンサー

以前の https://teratail.com/questions/207572 を参照いただければ、
だいたいイメージがわくと思います。

多くの通信操作は非同期処理となっております。
つまり、データ送受信部(通信)のコードは飛ばされて(実際は行なっている途中)、
その先のコードが先に実行されてしまいます。

なので、completionやDispatchQueue.main.asyncが用意されてます。

示されてるコードでは
self.tableView.reloadData()が、
do {} catch {}の後にあるので、通信中に先に実行され、
データ処理が完了前(namesが空の状態)で再読み込みがかかってて
結果、表示が0となっています。

なので、データ処理の中のprint(self.names) のすぐ後に
self.tableView.reloadData()を入れれば、
データ処理後にreloadがかかるようになり表示されるはずです。

修正
mainスレッドからにしなさいとエラーが出たので、
人(takabosoft)の受け売りになりますが、

Swift

1do { 2 // 間は省略 3 for value in jsons.values { 4 let value = value as! [String: Any] 5 self.names.append(value["name"] as! String) 6 } 7 DispatchQueue.main.sync { 8 self.tableView.reloadData() 9 return 10 } 11} catch { 12 print("error") 13} 14 15}) 16 17task.resume() // ここに引数(names: [String])は不要

これでどうでしょうか???

投稿2019/08/23 05:37

編集2019/08/23 06:07
hameji

総合スコア1380

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

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

mita0

2020/12/11 05:43 編集

ありがとうございます。 このように書きました。 self.tableView.reloadData() エラー?:UITableView.reloadData() must be used from main thread only task.resume(names: [String]) エラー:Argument passed to call that takes no arguments また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) self.tableView.reloadData() } catch{ print(error) } }) //taskを動かす task.resume(names: [String]) DispatchQueue.main.async { self.tableView } } }
mita0

2019/08/23 06:22

2019-08-23 15:19:41.778804+0900 test0814[5104:1088244] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier tableView - must register a nib or a class for the identifier or connect a prototype cell in a storyboard' このようなエラーがでます。 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) } DispatchQueue.main.async { self.tableView.reloadData() return } print(self.names) } catch{ print(error) } }) //taskを動かす task.resume() } }
hameji

2019/08/23 06:31 編集

'unable to dequeue a cell with identifier tableView' コンソールにあるように、上記のエラーです。調べてみてくださいね。 ちなみにさっきの修正していた箇所はうまくいってそうです。 コレはまた別の問題です。
mita0

2019/08/29 14:42

返事遅くなりすいません。 別問題でしたね。 ありがとうございます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問