How to stop current URLSession if multiple sessions have been created?

Hi all pretty new to swift,

I am creating a module in Swift connected to React Native. From react native I call a function which will return the status code (if found).

//React Native code
NativeModules.Testing.testURL("MyURL", (result) => { //do some stuff with result });

This all works perfectly, and I can call this function multiple times (passing in different URL's each time). What I am trying to achieve now is to stop the current session.

I know I can use:

//Swift code

But how would I know which current session needs to be stopped? For example in react native I have a list of 5 different websites. I click on each list item (website) which creates a new session (lets say it takes 10 seconds to fetch that website). If I want to stop session number 3 before a result is returned how would I go about that? Is there a way to keep track of current session from react native?

Basically in react native click the website > before result is returned > click again in react native to stop that session.

Any help is greatly appretiated. Thanks.

//swift Code

class Testing: NSObject {`

   @objc func testURL(_ tempUrl: NSString, callback: @escaping RCTResponseSenderBlock) {`

  func checkURL (url: String, completion: @escaping ((Int) -> Void)){
  guard let url = URL(string: url) else{
  let session = URLSession.init(delegate: nil, delegateQueue: OperationQueue.current)
  session.dataTask(with: url) { (data, response, err) in
    if err != nil {
    if data == nil {
    let httpResponse = response as? HTTPURLResponse
    if httpResponse?.statusCode != 200 {
    } else {

    checkURL( url: tempUrl as! String, completion: { isSuccess in
      //Callback sends response back to react native after above session task has finished

You can capture the session you're using in the completion handler and invalidate it there. However...

Using one URLSession per request is an anti-pattern specifically recommended against by Apple. URLSessions are rather heavy weight and shouldn't be created and then immediately thrown away. Instead, you should keep a single instance (or the smallest set of unique instances if your requests have such radically different requirements) in memory and use it to make all of your requests. I'd also recommend not using OperationQueue.current, since it's almost assuredly nil, as you're (probably) not inside an Operation. Instead, just create your single URLSession() and let URLSession create its own OperationQueue instead of accidentally using whatever queue you may be on.

Once you do this, early cancellation of the request is as simple as task.cancel(), which will return a URLError.cancelled instance, or actually be completed since the cancellation was too late to take effect. If you need to cancel per URL, keep a Dictionary of [URL: URLSessionTask] for the tasks you create and cancel the task associated with the URL if you need to.

Terms of Service

Privacy Policy

Cookie Policy