I have been trying to populate data from a JSON file in a UICollectionView using a storyboard. After I created my outlets I connected my image and labels to my UICollectionViewCell.swift and my Collection View to UICollectionView. But, I am getting an error,
Unexpectedly found nil while implicitly unwrapping an Optional value: file Music2/ViewController.swift, line 22.
Line 22 is below pointing to "collectionView.dataSoure = self
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
parseJson()
}
After that, I parsed my JSON file and added a "DispatchQueue.main.async" at the end of pasreJson() (not sure about the part). Would this pose a problem?
//JSON
private func parseJson(){
guard let path = Bundle.main.path(forResource: "data (1)", ofType: "json") else {
return
}
let url = URL(fileURLWithPath: path)
do{
let jsonData = try Data(contentsOf: url)
let userData = try JSONDecoder().decode(UserData.self, from: jsonData)
albums = userData.albums
playlists = userData.playlists
}catch{
print("error : \(error)")
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
Here is my complete View Controller :
class ViewController: UIViewController, UICollectionViewDataSource {
@IBOutlet weak var collectionView : UICollectionView!
//INSTANCE OF JSON DATA
var albums = [Album]()
var playlists = [Playlist]()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
parseJson()
}
//UICollectionView protocols
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection
section: Int) -> Int {
return albums.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath:
IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell",
for: indexPath) as! CollectionViewCell
cell.Label.text = albums[indexPath.row].title.capitalized
return cell
}
//JSON
private func parseJson(){
guard let path = Bundle.main.path(forResource: "data (1)", ofType: "json") else {
return
}
let url = URL(fileURLWithPath: path)
do{
let jsonData = try Data(contentsOf: url)
let userData = try JSONDecoder().decode(UserData.self, from: jsonData)
albums = userData.albums
playlists = userData.playlists
}catch{
print("error : \(error)")
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}