1

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

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
bomo
  • 39
  • 5
  • 1
    Surely you do not want to cancel it immediately? At some point in your code you would create a `Task { ... }` that involves calling whatever `async` method this code is in, right? You can cancel that `Task` instead. – Sweeper Apr 26 '23 at 09:22

1 Answers1

2

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

ftp27
  • 885
  • 1
  • 12
  • 31