Ios 未使用自动完成更新搜索结果
我正在swift中构建一个应用程序,需要能够搜索城市,我希望搜索能够与自动完成一起工作 因此,我首先在包含UISearch栏及其关联控制器的xib中创建一个视图控制器。我为视图控制器编写的类如下:Ios 未使用自动完成更新搜索结果,ios,swift,autocomplete,ios8,uisearchbar,Ios,Swift,Autocomplete,Ios8,Uisearchbar,我正在swift中构建一个应用程序,需要能够搜索城市,我希望搜索能够与自动完成一起工作 因此,我首先在包含UISearch栏及其关联控制器的xib中创建一个视图控制器。我为视图控制器编写的类如下: import UIKit class LocationViewController: UIViewController, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, UISearchControllerDelega
import UIKit
class LocationViewController: UIViewController, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, UISearchControllerDelegate {
// MARK: - Properties
var dirty: Bool = false
var loading: Bool = false
var suggestions: Array<String> = [] {
didSet {
searchDisplayController?.searchResultsTableView.reloadData()
}
}
// MARK: - Initialization
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
searchDisplayController?.searchBar.placeholder = "Ville ou adresse"
}
// MARK: - UISearchBarDelegate
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if countElements(searchText) > 0 {
if (loading) {
dirty = true
} else {
loadSearchSuggestions()
}
}
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
suggestions = []
}
// MARK: - Search backend
func loadSearchSuggestions() {
loading = true
var query = searchDisplayController?.searchBar.text
var urlEncode = query!.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
var urlString = "https://maps.googleapis.com/maps/api/place/autocomplete/json?key=MYAPIKEY&components=country:FR&input=\(urlEncode)"
var request = NSURLRequest(URL: NSURL(string: urlString)!)
var session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if (error != nil) {
self.loading = false
println(error.localizedDescription)
return
}
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &err) as Dictionary<String,AnyObject>
var predictions = jsonResult["predictions"] as Array<AnyObject>
var currentSug: Array<String> = []
for prediction in predictions {
var predDict = prediction as Dictionary<String, AnyObject>
var adress = predDict["description"] as String
currentSug.append(adress)
}
if err != nil {
println("JSON Error in search \(err!.localizedDescription)")
return
}
self.suggestions = currentSug
if self.dirty {
self.dirty = false
self.loadSearchSuggestions()
}
self.loading = false
})
task.resume()
}
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "suggestCell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as UITableViewCell?
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: cellIdentifier)
}
if suggestions.count > 0 {
cell!.textLabel!.text = suggestions[indexPath.row]
}
return cell!
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return suggestions.count
}
}
在某一点之前,一切正常。当我在我的搜索框中写一封信时,请求起作用,我得到的结果存储在我的建议变量中
唯一的问题是:包含结果的表视图没有按照建议变量的didSet中指定的那样重新加载。除非我尝试滚动空列表
现在,如果我键入第二个字符,我的表视图将显示仅键入一个字符时的结果。如果我尝试滚动,那么我会得到正确的结果
非常感谢您抽出时间回答我的问题。我可能在代码中犯了错误,因为我对swift和一般编程还是相当陌生。答案很简单,我看不到 对GoogleAPI的查询是异步完成的,而UI的更新则需要同步完成 以下是LoadSearchSuggestions中self.loading=false之后缺少的代码:
这就是诀窍,希望它能帮助别人 我看不到您在建议数组的didSet中调用tableView.reloadData。因此,每次更新数组时,它都应该重新加载表var建议:array=[]{didSet{searchDisplayController?.searchResultsTableView.reloadData}
self.loading = false
dispatch_async(dispatch_get_main_queue(), {
searchDisplayController?.searchResultsTableView.reloadData()
})