When I print dictionary["name"] it showed up as what I wanted, but if I append it to my class it appeared as nil, this also happened when I append dictionary["name"] as? String to an array here is my code:
class HomeController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
var test: [Test]?
@IBOutlet weak var cView: UICollectionView!
func fetchJSON () {
let url = URL(string: "My JSON File")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print("ERROR")
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
self.test = [Test]()
for dictionary in json as! [[String: AnyObject]] {
let tes = Test()
tes.name = dictionary["name"] as? String
tes.country = dictionary["country"] as? String
self.test?.append(tes)
}
}
catch {
print("ERROR")
}
}.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
fetchJSON()
}
override func viewDidAppear(_ animated: Bool) {
cView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return test?.count ?? 0
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! Cell
cell.nameLabel.text = test?[indexPath.item].name
cell.countryLabel.text = test?[indexPath.item].country
return cell
}
}