How to cancel a URL session request

后端 未结 3 889
野趣味
野趣味 2021-01-12 12:57

I am upload multiple image to server using convert image to base64 and send image in a API as a parameter. But when we call api again and again then how to stop api calling

相关标签:
3条回答
  • 2021-01-12 13:22

    Make the object task as a global variable, then you can cancel it anywhere by:

    task.cancel()
    

    Alternatively, if the object session is a URLSession instance, you can cancel it by:

    session.invalidateAndCancel()
    
    0 讨论(0)
  • 2021-01-12 13:22

    You can check result of your task. And if everything is alright you can

    task.resume()

    but if not

    task.cancel()

    0 讨论(0)
  • 2021-01-12 13:24

    If you don't want to allow API call again if there is any previous download is on progress, you can do as follows,

    Make your task(URLSessionDataTask type) variable as global variable in the class as follows,

    let task = URLSessionDataTask()
    

    Then on your button action do as below by checking the task download status,

    func uploadButtonPressed() {
        if task.state != .running {
            // Make your API call here
        } else {
            // Dont perform API call
        }
    }
    

    You can make use following states like running which is provide by URLSessionDataTask class and do action accordingly as per your need,

    public enum State : Int {
        case running
        case suspended
        case canceling
        case completed
    }
    
    0 讨论(0)
提交回复
热议问题