Swift async cancel like URLSession

291 Views Asked by At

when i use callback function with URLSession, i can use URLSessionDataTask to cancel a task

let task = URLSession.shared.dataTask(with: URLRequest(url: URL(string: "")!)) { data, response, error in
    // handle response
}
task.cancel()

when i use async func with URLSession, there is not any cancel method for it, how to cancel it before it completed

try await URLSession.shared.datafrom(from: URL(string: "")!)

i cannot found cancel method for async func for URLSession, i can check task cancel after task complete like this

try await URLSession.shared.data(from: URL(string: ""))
try Task.checkCancellation()

how to cancel URLSessionTask before it completed

1

There are 1 best solutions below

3
ftp27 On

You can cancel the whole operation

let task = Task {
    try await URLSession.shared.data(from: URL(string: ""))
}
task.cancel()

URLSessionDataTask should be canceled at the moment