Ich arbeite gerade an einer App und möchte die Daten von einer JSON-Webseite in einem TableView anzeigen ... Mein Code zum Speichern der JSON-Daten in einem Array funktioniert bereits wie ich sie jedes Mal in der Konsole drucken kann, aber die Daten nicht in der Tabellenansicht geladen und ich habe fast alles ausprobiert: Ändern der Zell-ID, mit benutzerdefinierten Zellen, etc ... Wer Ideen wie dieses Problem zu lösen?Swift 3 Lade JSON in Tabellenansicht
import UIKit
class TableViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var names: [String] = []
var rating: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
let url=URL(string:"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=51.0460761,3.7286716&radius=300&type=bar&key=AIzaSyCpHkY1s-qZjTOyTvDjMgD6hr5VTtEOgpU")
do {
let allContactsData = try Data(contentsOf: url!)
let allContacts = try JSONSerialization.jsonObject(with: allContactsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject]
if let arrJSON = allContacts["results"] {
for index in 0...arrJSON.count-1 {
let aObject = arrJSON[index] as! [String : AnyObject]
names.append(aObject["name"] as! String)
rating.append(aObject["id"] as! String)
}
}
print(names)
print(rating)
self.tableView.reloadData()
}
catch {
}
}
func tableView(_ tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return names.count;
}
func tableView(_ tableView: UITableView!, didSelectRowAtIndexPath indexPath: IndexPath!) {
print("You selected name : "+names[indexPath.row])
}
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell{
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
if !(cell != nil) {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
}
cell?.textLabel?.text=self.names[indexPath.row]
cell?.detailTextLabel?.text = self.rating[indexPath.row]
return cell!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
// Hide the navigation bar on the this view controller
self.navigationController?.setNavigationBarHidden(true, animated: true)
}
override func viewWillDisappear(_ animated: Bool) {
// Show the navigation bar on other view controllers
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
}
As you can see he gives me the 2 lists...
Sie tat Setzen Sie Ihren 'TableViewController' nicht als' dataSource' von 'tableView'. Das ist ein wichtiger Punkt, den Sie bei der Einrichtung Ihrer Schnittstelle verpasst haben. – luk2302