如何取消URL会话请求 [英] How to cancel a URL session request
本文介绍了如何取消URL会话请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用将图像转换为base64并向API发送图像作为参数,将多个图像上传到服务器.但是,当我们一次又一次调用api时,如何在单击按钮时停止api调用.我正在使用下面的代码来调用API.
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.
预先感谢
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()
推荐答案
将对象 task
设置为全局变量,然后可以通过以下任何方式将其取消:
Make the object task
as a global variable, then you can cancel it anywhere by:
task.cancel()
或者,如果对象 session
是 URLSession
实例,则可以通过以下方式取消它:
Alternatively, if the object session
is a URLSession
instance, you can cancel it by:
session.invalidateAndCancel()
这篇关于如何取消URL会话请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文