我是swift3.0的新手我正在实现自定义搜索框。我想知道如何建立搜索队列,以便在搜索框中的文本更改时,我需要使用新文本执行搜索操作,并且如果现有搜索操作正在取消取消。我还想包括阈值ontextchanged。因此,搜索操作不会经常被解雇
答案 0 :(得分:1)
你的问题在某种程度上是通用的,但是让我告诉你我是如何在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我检查是否在搜索框中输入了任何文本,如果是,我想确保从现在开始关闭任何其他任何正在进行的AFNetworking任务其中仍然在运行:
//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()
}
最后,如果错误代码不是failure
,我还会检查NSURLErrorCancelled
关闭。因为,如果发生这种情况,我不会显示任何错误消息或烤面包。
//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()
希望它有所帮助!