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
session.invalidateAndCancel()
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
@objc(Testing)
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{
return
}
let session = URLSession.init(delegate: nil, delegateQueue: OperationQueue.current)
session.dataTask(with: url) { (data, response, err) in
if err != nil {
completion(404)
return
}
if data == nil {
completion(404)
return
}
let httpResponse = response as? HTTPURLResponse
if httpResponse?.statusCode != 200 {
completion(httpResponse!.statusCode)
} else {
completion(httpResponse!.statusCode)
}
}.resume()
};
checkURL( url: tempUrl as! String, completion: { isSuccess in
//Callback sends response back to react native after above session task has finished
callback([isSuccess])
});
}
}