Search code examples
iosobjective-cswiftuitableviewavaudioplayer

UITableViewCell Image change after operation is finished


I have a problem about changing image when audio is finished. How i change the image of cell ? Please help me. I printed "Done" with 'audioPlayerDidFinishPlaying' but i dont know how to control the cell image or etc.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if messageList[indexPath.row].fileAudioUid != nil {
        let url = "..."
        startDownload(audioUrl: url)
    }
}


var audioPlayer : AVAudioPlayer!
func startDownload(audioUrl:String) -> Void {
    let fileUrl = self.getSaveFileUrl(fileName: audioUrl)
    let destination: DownloadRequest.DownloadFileDestination = { _, _ in
        return (fileUrl, [.removePreviousFile, .createIntermediateDirectories])
    }

    Alamofire.download(audioUrl, to:destination)
        .downloadProgress { (progress) in
            print(progress)
        }
        .responseData { (data) in
            let url1 = data.destinationURL?.absoluteURL
            print(url1!)
            do {
                self.audioPlayer = try AVAudioPlayer(contentsOf: url1!)
                self.audioPlayer.delegate = self
                self.audioPlayer.prepareToPlay()
                self.audioPlayer.play()
            }catch let error {
                print(error)
            }
    }
}

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    if flag {
        print("Done")
    } else {
        // did not finish successfully
    }
}

Solution

  • Retain a reference to the cell

    let cellRef: IndexPath?
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if messageList[indexPath.row].fileAudioUid != nil {
            let url = "..."
            startDownload(audioUrl: url)
            cellRef = indexPath
    
        }
    }
    

    Then

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        if flag {
            print("Done")
           let cell = tableView.cellForRow(at:cellRef)
           cell.image = "myImage.png"
        } else {
            // did not finish successfully
        }
    }