I'm having some problems when searching MPMediaItems. The code below will present the view and filter results. It will not clear the results when the search is cancelled (subsequent searches only add criteria to the already filtered data), change results while removing text (backspacing), or scroll beyond cells initially presented on the screen. How do I correct this to get the previously mentioned missing behavior? I've tried various things, including setting filteredTableData and pred to nil, but I'm obviously missing something major here. Any help is appreciated. Thanks in advance...
class SongsViewController: UIViewController, UISearchResultsUpdating {
@IBOutlet var songsTableView: UITableView!
var tableData = MPMediaQuery.songsQuery()
var song : MPMediaItem?
var tableDataToFilter = MPMediaQuery.songsQuery()
var filteredTableData : MPMediaItemCollection?
var resultSearchController : UISearchController!
var pred : MPMediaPropertyPredicate?
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: "SongCell", bundle: nil)
songsTableView.registerNib(nib, forCellReuseIdentifier: "cell")
resultSearchController = UISearchController(searchResultsController: nil)
resultSearchController.searchResultsUpdater = self
resultSearchController.dimsBackgroundDuringPresentation = true
resultSearchController.searchBar.sizeToFit()
songsTableView.tableHeaderView = self.resultSearchController.searchBar
songsTableView.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if resultSearchController.active {
let count = filteredTableData!.count
return count
} else {
if let collection = tableData.collections {
let collectionCount = collection.count
return collection.count
}
}
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : SongCell = self.songsTableView.dequeueReusableCellWithIdentifier("cell") as! SongCell
if resultSearchController.active {
song = filteredTableData!.items[indexPath.row]
let songName = song!.valueForProperty(MPMediaItemPropertyTitle) as! NSString
cell.songTitleLabel.text = songName as String
} else {
song = tableData.items![indexPath.row]
if song!.valueForProperty(MPMediaItemPropertyTitle) == nil {
cell.songTitleLabel.text = "Song Title is Blank" as String
} else {
let songName = song!.valueForProperty(MPMediaItemPropertyTitle) as! NSString
cell.songTitleLabel.text = songName as String
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
pred = MPMediaPropertyPredicate(value: searchController.searchBar.text!, forProperty: MPMediaItemPropertyTitle, comparisonType: MPMediaPredicateComparison.Contains)
tableDataToFilter.addFilterPredicate(pred!)
filteredTableData = MPMediaItemCollection(items: tableDataToFilter.items!)
self.songsTableView.reloadData()
}