私は、URLから受け取ったデータを保持する構造体を持っています。このコードはすべて、clubDictという辞書にデータを置くまでは問題なく動作しますが、tableViewにデータを表示すると、辞書のデータ数が取得されますが、表示されるのは1つのキーとその異なる値プロパティだけです繰り返す。辞書のすべてのデータをtableViewに取り込むにはどうすればよいですか?
struct Swifter: Codable {
let id: String?
let address: String?
}
class TableViewController: UITableViewController {
var clubDict: [String: Swifter] = [:]
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let locationDict: Dictionary<String, Any> = ["latitude" : 53.444101, "longitude" : -2.192934]
let json = ["location" : locationDict] as [String : Any]
guard let clubLocatorURL = URL(string: "https://us-central1-geofire-46ce2.cloudfunctions.net/Club-Locator") else { return }
var request = URLRequest(url: clubLocatorURL)
request.httpMethod = "POST"
guard let httpBody = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { return }
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print("Response: \(response)")
}
if let data = data {
do {
let decoder = JSONDecoder()
self.clubDict = try decoder.decode([String: Swifter].self, from: data)
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print("error: \(error)")
}
}
}.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return clubDict.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
for (key, value) in clubDict {
cell.textLabel?.text = key
cell.detailTextLabel?.text = value.address
}
return cell
}
}
あなたの方法は、テーブルにデータを表示するには間違っています。 'cellForRowAt'はインデックスパス(indexPath'パラメータ)ごとに1回、複数回呼び出されます。通常、データソースとして配列が使用されます。インデックスパスのオブジェクトを配列から取得し、データを表示するはずです。 – vadian