How to cancel DispatchQueue.main.asyncAfter(deadline: time) in Swift3? [duplicate]

早过忘川 提交于 2019-12-03 10:05:35

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)
    }

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!