gpt4 book ai didi

swift - 如何在用户需要时终止功能?

转载 作者:行者123 更新时间:2023-11-28 08:50:44 25 4
gpt4 key购买 nike

我有一个从网络获取数据的函数。但是,虽然执行此功能,但需要一段时间。因此我添加了一个停止按钮。但是如何在用户点击停止按钮时终止功能?

终止函数:

func getData(param: String) -> String{

//param can be one of these = row, name, channel, rating, share
var xPath: String = ""
if param == "row" {
xPath = "/html/body/table[4]/tr[4]/td[@class='sayfa_ic']/table/tr[2]/td/table//tr/td[1]/b"
} else if param == "name" {
xPath = "/html/body/table[4]/tr[4]/td[@class='sayfa_ic']/table/tr[2]/td/table//tr/td[2]"
} else if param == "channel" {
xPath = "/html/body/table[4]/tr[4]/td[@class='sayfa_ic']/table/tr[2]/td/table//tr/td[3]"
} else if param == "rating" {
xPath = "/html/body/table[4]/tr[4]/td[@class='sayfa_ic']/table/tr[2]/td/table//tr/td[4]"
} else if param == "share" {
xPath = "/html/body/table[4]/tr[4]/td[@class='sayfa_ic']/table/tr[2]/td/table//tr/td[6]"
} else {
return ""
}
let html = Ji(htmlURL: NSURL(string: URL!)!)//takes a while
let titleNode = html!.xPath(xPath)!
return String(titleNode)
}

最佳答案

如果您正在使用 NSURLSessionTask,请调用 task.cancel()

文档:

/* -cancel returns immediately, but marks a task as being canceled.
* The task will signal -URLSession:task:didCompleteWithError: with an
* error value of { NSURLErrorDomain, NSURLErrorCancelled }. In some
* cases, the task may signal other work before it acknowledges the
* cancelation. -cancel may be sent to a task that has been suspended.
*/

使用同步 API 会很困难;您需要一个异步 API,而调用 cancel 只会产生一个错误,不管出于何种原因都可能发生这种情况,您应该正确处理。

关于swift - 如何在用户需要时终止功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34272076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com