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

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

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

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

JSON

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

iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Swift

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

Q&A

解決済

1回答

1131閲覧

Swift4:カスタムTable ViewでFatal error: Unexpectedly found nil while unwrapping an Optional value

panyayan

総合スコア36

TableView

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

JSON

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

iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Swift

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

0グッド

0クリップ

投稿2018/10/02 03:56

現在カスタムTableViewを作成しケースごとに分けて表示しています。
各LabelにはAPIを叩いて取得したJsonデータが代入されています。
NavigationControllerを追加し他ところif let price:String = store![indexPath.row].priceと他のtime,closeddayの部分で
Unexpectedly found nil while unwrapping an Optional valueとエラーが出ました。
NavigationControllerを追加する前は問題なく動いていました。
これはAPIを叩いて取得したJsonが読み込みが完了する前に強制アンラップしているのが原因でしょうか。
またその場合の対処はどうすればいいでしょうか。よろしくお願いします。

TableView

1 var store_id = "" 2 var store : [Store]? 3 var photoPath : [Store.photos]? 4 var tag : [Store.tags]? 5 6override func viewDidLoad() { 7 super.viewDidLoad() 8 9 10 //Collectiopn DetaSources 11 imageCollectionView.dataSource = self 12 imageCollectionView.delegate = self 13 14 tagCollectionView.dataSource = self 15 tagCollectionView.delegate = self 16 17 //UIView Shadow 18 let shadowPath = UIBezierPath(rect: UIView.bounds) 19 UIView.layer.masksToBounds = false 20 UIView.layer.shadowColor = UIColor.black.cgColor 21 UIView.layer.shadowOffset = .zero 22 UIView.layer.shadowOpacity = 0.2 23 UIView.layer.shadowPath = shadowPath.cgPath 24 25 //Request API 26 let url = URL(string: "http://localhost:8000/store/api?store_id=" + store_id) 27 let request = URLRequest(url: url!) 28 let session = URLSession.shared 29 30 let encoder: JSONEncoder = JSONEncoder() 31 encoder.dateEncodingStrategy = .iso8601 32 encoder.outputFormatting = .prettyPrinted 33 34 session.dataTask(with: request){(data, response, error)in if error == nil, 35 let data = data, 36 let response = response as? HTTPURLResponse{ 37 38 let decoder: JSONDecoder = JSONDecoder() 39 decoder.dateDecodingStrategy = .iso8601 40 do { 41 42 let json = try decoder.decode(Store.self, from: data) 43 44 if json != nil { 45 print("JSON is Nil") 46 }else{ 47 print(json) 48 } 49 self.store = [json] 50 self.photoPath = json.photos 51 self.tag = json.tags 52 53 if let imageURL = URL(string: "http://127.0.0.1:8000/photos/" + json.photos[0].path){ 54 DispatchQueue.global().async { 55 let data = try? Data(contentsOf: imageURL) 56 if let data = data { 57 let image = UIImage(data: data) 58 DispatchQueue.main.async { 59 self.mainImage.image = image 60 } 61 } 62 } 63 } 64 65 DispatchQueue.main.async { 66 self.nameLabel.text = json.name 67 self.locationLabel.text = json.location 68 69 } 70 71 } catch { 72 print("error:", error.localizedDescription) 73 74 } 75 76 } 77 78 }.resume() 79} 80 81 82func numberOfSections(in tableView: UITableView) -> Int { 83 return 3 84 } 85 86 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 87 switch section { 88 case 0: 89 return 1 90 case 1 : 91 return 1 92 case 2 : 93 return 1 94 default: 95 return 0 96 } 97 } 98 99func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 100 101 let cell = UITableViewCell() 102 103 switch indexPath.section { 104 case 0 : 105 //Price Cell 106 let priceCell = tableView.dequeueReusableCell(withIdentifier: "priceCell", for: indexPath) as? priceTableViewCell 107 108 if let price:String = store![indexPath.row].price{ 109 priceCell?.priceLabel.text! = price 110 }else{ 111 priceCell?.priceLabel.text! = "-" 112 } 113 return priceCell! 114 115 case 1 : 116 //timeCell 117 118 let timeCell = tableView.dequeueReusableCell(withIdentifier: "timeCell", for: indexPath) as? timeTableViewCell 119 120 if let time:String = store![indexPath.row].open_time{ 121 timeCell?.timeLabel.text! = time 122 }else{ 123 timeCell?.timeLabel.text! = "-" 124 } 125 return timeCell! 126 127 case 2 : 128 //closedayCell 129 let closedayCell = tableView.dequeueReusableCell(withIdentifier: "closedayCell", for: indexPath) as? closedayTableViewCell 130 131 if let closeday:String = store![indexPath.row].closed_day{ 132 closedayCell?.closedayLabel.text! = closeday 133 }else{ 134 closedayCell?.closedayLabel.text! = "-" 135 } 136 137 138 return closedayCell! 139 140 default : 141 print("Default Selected") 142 } 143 return cell 144 }

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

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

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

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

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

guest

回答1

0

ベストアンサー

APIを叩いて取得したJsonが読み込みが完了する前に強制アンラップしているのが原因でしょうか

そうです。

読み込みが完了していないのにnumberOfRows(inSection:)で1以上の値を返しているのが原因です。
読み込みが完了するまでは0を返すようにして下さい。

もしくは、読み込みが完了するまではセル生成時にstoreを参照しないことです。(セルに何も表示しない、「読み込み中」を表示させる、など)

投稿2018/10/02 04:14

fuzzball

総合スコア16731

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

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

panyayan

2018/10/02 04:53

ご回答ありがとうございます。 >セルに何も表示しない、「読み込み中」を表示させる、など この部分についてどうコードに書けばいいのかわからないのでお手数ですが、参考になるようなサイトを教えて頂けると嬉しいです
fuzzball

2018/10/02 05:03 編集

>>どうコードに書けばいいのかわからない 「セルに何も表示しない」であれば、何もコードを書かなければいいです。 「読み込み中を表示させる」であれば、「読み込み中です」のラベルを置けばいいです。
panyayan

2018/10/02 05:07

すみません言葉足らずでした >「読み込み中」を表示させる こちらについての参考など教えていただきたいです
fuzzball

2018/10/02 05:15

すでに13:58のコメントに追記しています。
panyayan

2018/10/02 05:20

すみません見落としていました。ありがとうございます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問