如何在Swift3中取消DispatchQueue.main.asyncAfter(deadline:time)? [英] How to cancel DispatchQueue.main.asyncAfter(deadline: time) in Swift3?

查看:1301
本文介绍了如何在Swift3中取消DispatchQueue.main.asyncAfter(deadline:time)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在使用以下代码来查看用户是否已停止在searchBar中键入内容.每当用户在0.5秒后立即开始键入命令时,我都想取消它.

I'm currently using the following code to see if the user has stopped typing in the searchBar. I would like to cancel it everytime the user immediately starts typing after 0.5 seconds.

代码:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
    // your function here
}

问题:

如果用户开始在Swift3中再次输入,如何取消DispatchQueue.main.asyncAfter?

Question:

How do I cancel DispatchQueue.main.asyncAfter if the user starts typing again in Swift3 ?

我以前曾尝试实现:

NSObject.cancelPreviousPerformRequests(withTarget: self)
self.perform(Selector(("searchForText:")), with: searchString, afterDelay: 0.5)

但是,延迟似乎无法正常工作.

However the delay does not seem to work properly.

更多代码:

//In class SearchViewController: UITableViewController, UISearchResultsUpdating
func updateSearchResults(for searchController: UISearchController) {
    let searchString: String = searchController.searchBar.text!

    //This is what I previously tried.. which doesn't work...
    //NSObject.cancelPreviousPerformRequests(withTarget: self)
    //self.perform(Selector(("searchForText:")), with: searchString, afterDelay: 0.5)

    //A struct with the first example code shown above.
    Utils.Dispatch.delay(secondsToDelay: 1){
        print("1 second has passed ! " + searchString)
    }
}

推荐答案

对于那些有时间测试代码的人,我将发布未经测试的当前解决方案.有时间尝试时,我将编辑帖子.

For those that have time to test code, I'll post my current solution that is untested. When I have time to try it, I'll edit the post.

private var operationQueue: OperationQueue!
private var mainAsyncQueue: DispatchQueue?


override func viewDidLoad() {
    print("ViewDidLoad of SearchViewController called")

    self.operationQueue = OperationQueue()
    self.currentTime = DispatchTime.now()

}
// MARK: UISearchResultsUpdating

func updateSearchResults(for searchController: UISearchController) {
    let searchStringRaw: String = searchController.searchBar.text!
    let searchString = searchStringRaw.trimmingCharacters(in: .whitespacesAndNewlines)
    guard searchString.characters.count > 0 else {
        return
    }

    print("Search string: \(searchString)")
    self.operationQueue.cancelAllOperations()
    //Put this in Utils.Dispatch.Delay
    self.mainAsyncQueue = DispatchQueue(label: "search.operation." + String(describing: DispatchTime.now()), qos: .default, attributes: DispatchQueue.Attributes.concurrent)

    let time = DispatchTime.now()
    self.currentTime = time

    self.mainAsyncQueue!.asyncAfter(deadline: time + 1){
        guard self.currentTime == time else {
            return
        }

        let tempOperation = BlockOperation(block:{

            if let nsurl: URL = Utils.Url.generate(Constants.Url.Search, options: "&p=1&n=20&q="+searchString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!){
                //Download data and handle response

            } else {
                print("Something went wrong...")
            }


        })
        self.operationQueue.addOperation(tempOperation)
    }

}

这篇关于如何在Swift3中取消DispatchQueue.main.asyncAfter(deadline:time)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆