user1591668 user1591668 - 1 month ago 6
iOS Question

IOS swift how can I populate my TableView with Json data being returned

I have just started working with Swift and am able to do some basic things. Right now I am trying to populate my UITableView with Json Data that I am successfully retrieving. Right now I have this simple Table that looks like this

enter image description here

That is a basic TableView that I was able to create with this code

@IBOutlet var StreamsTableView: UITableView!

let groceries = ["Fish","lobster","Rice","Beans"]




func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let mycell:UITableViewCell = StreamsTableView.dequeueReusableCell(withIdentifier: "prototype1", for: indexPath)

mycell.textLabel?.text = groceries[indexPath.row]
return mycell
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return groceries.count
}

override func viewDidLoad() {
super.viewDidLoad()
StreamsTableView.dataSource = self
}


I now have a JsonRequest that I am completing successfully using this code below

override func viewDidLoad() {
super.viewDidLoad()
StreamsTableView.dataSource = self

// Do any additional setup after loading the view.

var names = [String]()
let urlString = "http://localhost:8000/streams"

let url = URL(string: urlString)
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
if error != nil {
print(error)
} else {
do {

let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
if let Streams = parsedData["Streams"] as! [AnyObject]? {

for Stream in Streams {
if let post = Stream["post"] as? String {
names.append(post)
}
}
}

} catch let error as NSError {
print(error)
}
print(names)
}

}).resume()

}


What I essentially like to do is put the value of

let post = Stream["post"] as? String


inside the TableView instead of the Groceries array . As I stated before the value is coming back from the Json, I just have not found any way that I could put that value inside the TableView any help would be great . I am using swift 3.0 .

Lu_ Lu_
Answer

Add reloading data code

DispatchQueue.main.async {
    StreamsTableView.reloadData()
}

just after your for loop

for Stream in Streams { ... 
Comments