我按如下方式从服务器加载json信息,但是当我单击鼠标太快转到另一个页面时,请求将继续在后台尝试,并且警告说viewController不再存在。如何取消onViewDisappear上的所有请求?
if let requestURL = URL(string: "https://www.example.com/file.php") {
var urlRequest = URLRequest(url: requestURL)
urlRequest.httpMethod = "POST"
let postString = "email=\(loginUsername.text!)"
urlRequest.httpBody = postString.data(using: .utf8)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest as URLRequest) { (data, response, error) in
if let data = data {
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] {
// Async Stuff
DispatchQueue.main.async{
// do things
}
DispatchQueue.main.async(execute: {
})
}
} catch {
print("Error: \(error)")
}
}
}
task.resume()
}
答案 0 :(得分:1)
将您的请求保存在某个地方,然后远离控制器调用:
task.cancel()
答案 1 :(得分:0)
您可以使用2种方式
使用task.cancel()
使用task.suspend()
task.cancel()
在做Cancels the task.
task.suspend()
在做Temporarily suspends a task.
答案 2 :(得分:0)
class DataCall {
var task: URLSessionDataTask?
func load() {
guard let requestURL = URL(string: "https://www.example.com/file.php") else { return }
var urlRequest = URLRequest(url: requestURL)
urlRequest.httpMethod = "POST"
let postString = "email=\(loginUsername.text!)"
urlRequest.httpBody = postString.data(using: .utf8)
let session = URLSession.shared
task = session.dataTask(with: urlRequest as URLRequest) { (data, response, error) in
if let data = data {
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] {
// Async Stuff
DispatchQueue.main.async{
// do things
}
}
} catch {
print("Error: \(error)")
}
}
}
task.resume()
}
func stopTask() {
task.cancel()
}
}
然后在您的viewWillDissapear
中致电dataCall.stopTask()
。