Show images in cells from array

Viewed 64

I have TableViewController and AudioPlayerViewController. In TableViewController I want to know how many tracks have been listened to. And show the image in the listened cells TableViewController. To detect that track have been listened I use this code in AudioPlayerViewController:

func audioPlayerDidFinishPlaying(_ audioPlayer: AVAudioPlayer, successfully flag: Bool) {
     UserDefaults.standard.set( arrayOfListened(trackIndex), forKey: "key") 
}

And to show image in listened cells in TableViewController next:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: String(format: "cell", indexPath.row), for: indexPath) as! MasterViewCell

    if indexPath.row == arrayOfListened[indexPath.row] {
        cell.cellStatusImage.image = UIImage(named: "statusDone.png")
    }
                
}

But my app crashed. How to fix it?

1 Answers

The problem is that you are trying to get an element from the array by indexPath.row which probably doesn't exist. Try to use something like this:

...

guard 
    arrayOfListened.indices.contains(indexPath.row), 
    indexPath.row == arrayOfListened[indexPath.row] 
else {
    return cell
}

... your cell configuration

Or, if your arrayOfListened just contains song IDs, you can simply use:

if arrayOfListened.contains(indexPath.row) {
    ... your cell configuration
}
Related