Swift 如何在用户需要时终止函数?
我有一个从web获取数据的函数。但是当这个函数执行时,它需要一段时间。因此,我添加了一个停止按钮。但是,当用户点击停止按钮时,如何终止函数 要终止的函数:Swift 如何在用户需要时终止函数?,swift,Swift,我有一个从web获取数据的函数。但是当这个函数执行时,它需要一段时间。因此,我添加了一个停止按钮。但是,当用户点击停止按钮时,如何终止函数 要终止的函数: func getData(param: String) -> String{ //param can be one of these = row, name, channel, rating, share var xPath: String = "" if param == "row"
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只会创建一个错误,不管出于何种原因,都可能会发生这种情况,您应该正确处理这种情况 如果您正在使用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只会创建一个错误,不管出于何种原因,都可能会发生这种情况,您应该正确处理这种情况 你得给我们更多。你能发布你引用的函数吗?我不明白你为什么需要更多的信息。他有这个功能,随时都想停止。代码不多并不意味着这是个坏问题。你必须给我们更多。你能发布你引用的函数吗?我不明白你为什么需要更多的信息。他有这个功能,随时都想停止。代码不多并不意味着这是个坏问题。