2017-04-02 100 views
1

我是新的swift3.0我正在实现一个自定义搜索框。我希望知道如何创建一个搜索队列,以便在搜索框中更改文本时,我需要使用新文本执行搜索操作,并且如果存在现有的搜索操作,则取消该操作。我也想包含阈值ontextchanged。因此,搜索操作不会非常频繁地被触发如何实现搜索队列

+0

所以'UISearchController'有什么问题? :/ –

+0

@agent_stack我希望创建一个像uber应用程序一样的自定义用户界面。 –

+0

所以你想textField用户可以在哪里搜索位置?我是对的吗? –

回答

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

希望它有帮助!

+0

谢谢这有助于HTTP请求和响应方面,但我实际上正在调查更通用的,我可以添加任何任务,并取消它,如果新的任务进来。 –