如何实现搜索队列



我是 swift3.0 的新手,我正在实现一个自定义搜索框。我想知道如何制作搜索队列,以便在搜索框中的文本更改时,我需要对新文本执行搜索操作,如果正在进行现有的搜索操作,请取消该操作。我还想在文本上包含阈值更改。这样搜索操作就不会经常被触发

你的问题有点笼统,但让我告诉你我是如何在 Swift 3 和 AFNetworking 中做到这一点的(这假设您希望在服务器上搜索数据(。

我在视图控制器的属性中保留了网络管理器的引用:

//The network requests manager. Stored here because this view controller extensively uses AFNetworking to perform live search updates when the input box changes.
var manager = AFHTTPRequestOperationManager()

之后,使用UISearchController,我检查搜索框中是否输入了任何文本,如果是,我想通过关闭任何仍在运行的任务来确保从现在开始没有任何其他正在进行的AFNet工作任务:

//Called when the something is typed in the search bar.
func updateSearchResults (for searchController: UISearchController) {
    if !SCString.isStringValid(searchController.searchBar.text) {
        searchController.searchResultsController?.view.isHidden = false
        tableView.reloadData()
        return
    }
    data.searchText = searchController.searchBar.text!
    /**
        Highly important racing issue solution. We cancel any current request going on because we don't want to have the list updated after some time, when we already started another request for a new text. Example:
        - Request 1 started at 12:00:01
        - We clear the containers because Request 2 has to start
        - Request 2 started at 12:00:02
        - Request 1 finished at 12:00:04. We update the containers because data arrived
        - Request 2 finished at 12:00:05. We update the containers because data arrived
        - Now we have data from both 1 and 2, something really not desired.
     */
    manager.session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
        dataTasks.forEach { $0.cancel() }
    }
    /**
        Reloads the list view because we have to remove the last search results.
     */
    reloadListView()
}

最后,如果错误的代码未NSURLErrorCancelled,我还检查failure关闭。因为,如果发生这种情况,我不会显示任何错误消息或 toast。

 //The operation might be cancelled by us on purpose. In this case, we don't want to interfere with the ongoing logic flow.
 if (operation?.error as! NSError).code == NSURLErrorCancelled {
    return
 }
 self.retrieveResultListFailureNetwork()

希望对您有所帮助!

最新更新