How to stop the request before recall it again?

I have a timer which calls the function every afew seconds.
I have to check first, if the first request in proccess, so I have to stop it before send again new request
here is my code :slight_smile:

@objc func getLocation(){

    let url = "http://myweb,com/test.php"
    request(url,method:.get,parameters:nil,encoding: JSONEncoding()).responseJSON
            response in switch response.result{
            case .success(let JSON2):

// - - -

the same thing here if i use Alamofire :thinking:

func getData() {
    let url1 = URL(string: "")
    Alamofire.request(url1!).responseJSON { (response) in
        let result =
        do {
            self.Messages = try JSONDecoder().decode([Messages_Struct].self, from: result!)
            for message1 in self.Messages{
                print("Name : ",
        }catch {

I can’t really speak to the code you posted because it’s using various third-party frameworks. I can, however, discuss the on-the-wire aspects of this. And the key factor there is whether you’re using HTTP/2 or not.

HTTP 1.1 has no way to cancel an in-flight request. The only cancellation option for the client is to drop the connection. And the fundamental problem with that is that the bandwidth you save by cancelling the request tends to get lost in re-establishing the connection. Worse yet, re-establishing the connection results in higher latency for any subsequent requests. So in many cases it’s better to let an old request run and then throw away the results rather than cancel it.

On the other hand, if you can guarantee that you’re talking to an HTTP/2 server, it might make sense to cancel your old request before issuing the new one.

Regardless, this is somewhat off-topic for Swift Forums. If you’d care to pop over to the Core OS > Networking area of DevForums, I’d be happy to go into more detail there.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + ""

1 Like

You can use throttle on getLocation() to help guarantee that subsequent request is not repeated.

Here are example implementations you might want to check: