我一直在尝试使用故事板在UICollectionView中填充JSON文件中的数据。在我创建我的出口后,我连接我的图像和标签到我的UICollectionViewCell.swift和我的集合视图到UICollectionView。但是,我得到一个错误,
在隐式展开可选值时意外发现nil:文件Music2/ViewController.swift,第22行。
下面的第22行指向"collectionView。dataSoure = self
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
parseJson()
}
之后,我解析了我的JSON文件,并添加了"DispatchQueue.main.async"在pasreJson()的末尾(不确定部分)。这会造成问题吗?
//JSONprivate 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()
}
}
}
这是我完整的视图控制器:
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()
}
}
}
如果你在collectionView.dataSource = self
行上崩溃,那么你没有将集合视图连接到故事板中的视图控制器。打开你的故事板,从集合视图control-drag到视图控制器