NYTimes APIからJSONを読み込む関数があります。表の見出しに見出しを挿入しようとしています。これは、関数である:私はcell.textLabelをハードコーディングした場合、私はアプリを実行し、headlines
配列が適切に移入され見ることができます解析されたJSONの配列を読み込もうとするとインデックスが範囲外になる
func getJSON() {
let url = NSURL(string: nyTimesURL)
let request = NSURLRequest(url: url as! URL)
let session = URLSession(configuration: URLSessionConfiguration.default)
let task = session.dataTask(with: request as URLRequest) { (data, response, error) in
if error != nil {
print(error)
}
let json = JSON(data: data!)
let results = json["results"].arrayValue
for title in results {
let titles = title["title"].stringValue
print(titles)
let count: Int = title.count
self.numberOfStories = count
self.headlines.append(titles)
self.tableView.reloadData()
print("\n\n\nHeadlines array: \(self.headlines)\n\n\n")
}
}
task.resume()
}
そしてクラス変数として、私は
var headlines = [String]()
var numberOfStories = 1
を持っているすべての見出し。しかし、セルのラベルをself.headlines[indexPath.row]
に設定しようとすると、範囲外のクラッシュのインデックスが取得されます。私はtableView.reloadData()
コールをメインスレッド(DispatchQueue.main.async{}
)に入れてみましたが、それは問題ではありません。
ヘッドラインを正しく表示するにはどうすればよいですか?
ありがとうございました!
EDIT:テーブルビュー方式:
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.numberOfStories
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "JSONcell", for: indexPath) as! JSONTableViewCell
cell.cellLabel.text = self.headlines[indexPath.row]
return cell
}
投稿したコードのどれもが配列にアクセスしようとしません。あなたは実際に 'self.headlines [indexPath.row]'をどこで呼びますか?いつ、どこで 'getJSON'を呼び出しますか? – rmaddy
そして、 'DispatchQueue.main.async'を使ってデータタスク完了ブロックの中から' reloadData'を呼び出す必要があります。 – rmaddy
@rmaddy私は自分のtableviewメソッドを追加しました - 私は 'cellForRow'メソッドで' self.headlines [indexPath.row] 'を呼び出してラベルを設定します。 – KingTim