【问题标题】:integrate UISearchController with Async result update in swift将 UISearchController 与 swift 中的异步结果更新集成
【发布时间】:2016-06-05 10:52:28
【问题描述】:

我想实现 UISearchContoller,它使用 swifty json 从 webservice JSON 搜索,就像苹果的 appStore 当你搜索一个应用程序时,它加载而不将它们加载到 tableView 中

这是我在 updateSearchResultsForSearchController 方法中所做的:

func updateSearchResultsForSearchController(searchController: UISearchController) {
    filterContentForSearchText(searchController.searchBar.text!)
}


func filterContentForSearchText(searchText: String) {
filteredContents = myStruct.filter{$0.name.rangeOfString(searchText) != nil

} 

【问题讨论】:

    标签: json swift uisearchcontroller swifty-json


    【解决方案1】:

    发布更多您的代码会很好,就像您用于从 Web 服务获取结果一样,但是,无论如何我都会尝试引导您完成它。

    在使用 UISearchBar 和它的委托方法之前,我已经完成了,用户按下搜索按钮或输入,我会使用 NSURLSession 将用户的搜索词传递给 API,并解析响应。

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        let searchText : String = searchBar.text
        webService.getRecipe(ingredient: searchText, completionHandler: { (recipeArray) in
                self.highProteinArray = recipeArray
                dispatch_async(dispatch_get_main_queue(), {
                    self.collectionView.reloadData()
                })
            })
    }
    

    如您所见,我使用回调来处理将新解析的数据设置为变量以供以后使用,然后重新加载 collectionView。这样,您的 tableView/collectionView 将在您等待来自 Web 服务的响应然后解析它时加载并自行设置,一旦完成,您只需重新加载以显示新数据。

    要添加一点额外内容,您甚至可以在 cellForItemAtIndexPath 或 cellForRowAtIndexPath 中添加淡入动画,无论您使用的是哪个。

    【讨论】:

    • 感谢您的回答@jacob,我最终所做的是我调用了我的异步方法,该方法连接到 Web 服务以在 updateSearchResult 中接收 JSON 结果,因此每次在 searchBar 中插入一个新字符api调用并接收新结果
    猜你喜欢
    • 1970-01-01
    • 2022-09-29
    • 2013-10-06
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多