How to cancel a URL session request

…衆ロ難τιáo~ 提交于 2020-07-18 18:14:54

问题


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 on button click. I am using below code to call API.

Thanks in advance

let urlPath: String = "URL"
        let url: URL = URL(string: urlPath)!
        var request1 = URLRequest(url: url)
        request1.httpMethod = "POST"
        let stringPost="imgSrc=\(image)"
        let data = stringPost.data(using: String.Encoding.utf8)
        // print("data\(data)")
        request1.httpBody=data

        request1.timeoutInterval = 60
        let _:OperationQueue = OperationQueue()
        let task = session.dataTask(with: request1){data, response, err in
            do
            {
                if data != nil
                {
                    print("data\(String(describing: data))")
                    if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
                    {
                        DispatchQueue.main.async
                            {
                        print("json\(jsonResult)")


                    }
                }

            }
            catch let error as NSError
            {
                DispatchQueue.main.async
                    {

                print("error is \(error)")
                print("error desc \(error.localizedDescription)")
                }
            }}
        task.resume()

回答1:


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()



回答2:


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
}



回答3:


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

task.resume()

but if not

task.cancel()



来源:https://stackoverflow.com/questions/46617961/how-to-cancel-a-url-session-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!