How to I cancel a task created by the new Swift `async` keyword and closure, after the fact?

I'm experimenting with async/await on some existing code and would like to cancel an async thumbnail download if the table-view cell needs to be re-used. The problem is that I don't know how to declare storage for the handle so I can cancel it later on. See the attached code.


class PhotoCell: UITableViewCell {
    @IBOutlet weak var albumLabel: UILabel!
    @IBOutlet weak var photoIdLabel: UILabel!
    @IBOutlet weak var thumbnailImageView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!

    private static var imageLoader = ImageLoader()

//    private var task: Handle<(), Never>?

    override func prepareForReuse() {

//        task?.cancel()
        albumLabel.text = ""
        titleLabel.text = ""
        photoIdLabel.text = ""
    }

    // MARK: - Public Methods
    func configure(with photo: JPPhoto) {
        albumLabel.text	= "#\(photo.albumId.rawValue)"
        titleLabel.text	= photo.title
		photoIdLabel.text	= "#\(photo.id.rawValue)"
        thumbnailImageView.image = UIImage(systemName: "photo")

        /* task = */async {
            if let image = await PhotoCell.imageLoader.loadImage(from: photo.thumbnailUrl) {
                thumbnailImageView.image = image
            }
        }
    }
}
Answered by statemachinejunkie in 678575022

The solution was provided by "_Agent". I was missing the full type name task handle. A case of mental blindness.

Note that this class is decorated with @MainActor which was somehow dropped in the cut & paste.

What's wrong with the code you've commented out? Though I think the type ought to be Task.Handle<…>.

The code I commented out doesn't work because Task. was missing. You provided the solution. Thank you. Anyone know how to mark a topic or thread as closed?

Accepted Answer

The solution was provided by "_Agent". I was missing the full type name task handle. A case of mental blindness.

How to I cancel a task created by the new Swift `async` keyword and closure, after the fact?
 
 
Q