大家!我想在 1 秒后取消加载图像,或者通过用户操作(例如)取消加载图像并显示加载的图像。
这就是我所做的:
enum DownloadError: Error {
case invalidStatusCode
case badImage
case unknown
}
func downloadImageWithImageId(imageId: Int) async throws -> UIImage {
let imageUrl = URL(string: "https://github.com/yavuzceliker/sample-images/blob/main/images/image-\(imageId).jpg?raw=true")!
let imageRequest = URLRequest(url: imageUrl)
let (data, response) = try await URLSession.shared.data(for: imageRequest)
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode != 200 {
throw DownloadError.invalidStatusCode
}
guard let image = UIImage(data: data) else {
throw DownloadError.badImage
}
return image
}
func reloadImages() {
imageShowingTask = Task {
images = []
await view?.reloadImages()
do {
await view?.showSpinner(isLoading: true)
var imagesLoaded = [UIImage]()
for i in 1...5 {
async let image = try downloadImageWithImageId(imageId: i)
if Task.isCancelled {
print("---CANCELLED")
break
}
try await imagesLoaded.append(image)
}
self.images = imagesLoaded
await view?.showSpinner(isLoading: false)
await view?.reloadImages()
} catch (let error) {
print(error.localizedDescription) // here I want to detect error by URLSession
}
}
Task {
sleep(1)
imageShowingTask?.cancel()
}
}
但是我没有得到“---取消”打印,而是在
catch
块中得到了“取消”打印。
所以取消是不行的。预先感谢!
您应该捕获取消任务时抛出的 CancelationError,而不是检查 isCancelled
} catch is CancellationError {
print("---CANCELLED")
}