Reputation: 10172
This is the searchbar delegate that i use
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.characters.count >= 2 {
self.setupinbox(searchText)
}
}
This is the function to get data from server
func setupinbox(q : String) {
arrayOfRels.removeAll(keepCapacity: false)
self.tableView.reloadData()
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: "URL")!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
let data = "devicetoken=\(devicetoken!)&q=\(q)&user_id=\(userid)"
request.HTTPBody = data.dataUsingEncoding(NSUTF8StringEncoding)
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
let res = response as! NSHTTPURLResponse
dispatch_async(dispatch_get_main_queue(), {
if (res.statusCode >= 200 && res.statusCode < 300)
{
do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers ) as! NSArray
let json = JSON(jsonData)
for (_, subJSON): (String, JSON) in json[0]["interests"] {
let title = subJSON["title"].string
let eID = subJSON["ID"].string
let count = subJSON["count"].string
let rel1 = InboxInterests(title: title!,eventID : NSInteger(eID!)!, count: count!)
self.arrayOfRels.append(rel1)
}
} catch let error as NSError {
print(error)
}
self.tableView.reloadData()
} else {
let alert = UIAlertController(title: "Error", message: "Connection Failed", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction) in
}))
self.presentViewController(alert, animated: true, completion: nil)
}
}
)}
})
task.resume()
}
When i type searchbar slowly, everything is ok, i see results correctly.
But when i type 2 letters very quickly, i get duplicate item.
I also get duplicate items when i remove letters quickly
Tried something like delaying the textDidChange
but it didnt work.
Any idea what causes this and how can i fix?
Upvotes: 2
Views: 284
Reputation: 154
You should put an extra line of code:
do {
arrayOfRels.removeAll(keepCapacity: false)
........
Upvotes: 1