Reputation: 21
I want to show data but when run I can't show anything
import UIKit
class AnimalTableViewController: UITableViewController {
final let urlString = "https://doc-00-4k-docs.googleusercontent.com/docs/securesc/ha0ro937gcuc7l7deffksulhg5h7mbp1/ncme2210ej4sg6n7p7ipm3bmm6mht9s8/1568275200000/00096549938281215637/*/1aE90llwaDYEGS9Ci3nSmBUfaD75Rf6PD?e=download"
var nameArray = [String]()
var catArray = [String]()
var imgURLArray = [String]()
override func viewWillAppear(_ animated: Bool) {
downloadJsonWithURL()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nameArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "AnimalsCell") as! TableViewCell
cell.nameLabel.text = nameArray[indexPath.row]
cell.catLabel.text = catArray[indexPath.row]
let imgURL = NSURL(string: imgURLArray[indexPath.row])
if imgURL != nil {
let data = NSData(contentsOf: (imgURL as URL?)!)
cell.imgView.image = UIImage(data: data! as Data)
}
return cell
}
func downloadJsonWithURL() {
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
print(jsonObj.value(forKey: "animals")!)
if let actorArray = jsonObj.value(forKey: "animals") as? NSArray {
for actor in actorArray{
if let actorDict = actor as? NSDictionary {
if let name = actorDict.value(forKey: "name") {
self.nameArray.append(name as! String)
}
if let name = actorDict.value(forKey: "category") {
self.catArray.append(name as! String)
}
if let name = actorDict.value(forKey: "image") {
self.imgURLArray.append(name as! String)
}
}
}
}
OperationQueue.main.addOperation({
self.tableView.reloadData()
})
}
}).resume()
}
}
Upvotes: 0
Views: 97
Reputation: 51973
Use Dispatchqueue instead of OperationQueue
DispatchQueue.main.async {
and create one array containing a struct instead of using 3 separate arrays
struct Animal {
let name: String
let category: String
let image: String
}
and don't use NS classes
//...
if let animals = jsonObj.value(forKey: "animals") as? [Any] {
for actor in animals {
if let actorDict = actor as? [String: Any] {
animal = Animal()
if let name = actorDict["name"] as? String {
animal.name = name
}
if let category = actorDict["category"] as? String {
animal.category = category
}
if let imageUrl = actorDict["image"] as? String {
animal.imageUrl = imageUrl
}
self.animalArray.append(animal)
}
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
})
where self.animalArray is
var animalArray: [Animal]
Upvotes: 1