Reputation: 333
I want to fill a tableView
with the last heard songs. With .nowPlayingItem
I can get the very last song, but how can I get the songs heard before?
I think this question already has an answer at Retrieve list of songs ordered by last play time in iOS, but it is in Objective-C and I´m not able to translate it. Or is there an even better way to do it in Swift instead?
Upvotes: 0
Views: 313
Reputation: 13619
You could do something like this:
let startTime: NSTimeInterval = NSDate().timeIntervalSince1970
let songsQuery: MPMediaQuery = MPMediaQuery.songsQuery()
let songsArray: [MPMediaItem] = songsQuery.items!
let songsNSArray : NSArray = NSArray(array: songsArray)
let descriptor: NSSortDescriptor = NSSortDescriptor(key: MPMediaItemPropertyLastPlayedDate, ascending: false)
let sortedResults: NSArray = songsNSArray.sortedArrayUsingDescriptors([descriptor])
let finishTime: NSTimeInterval = NSDate().timeIntervalSince1970
NSLog("Execution took %f seconds to return %i results.", finishTime - startTime, sortedResults.count)
The results would be stored in the sortedResults array
Upvotes: 3
Reputation: 21134
This is how you can do it in Swift,
let start = NSDate().timeIntervalSince1970
let songsQuery = MPMediaQuery.songsQuery()
if let songsArray = songsQuery.items {
let sortedArray = songsArray.sort { item1, item2 in
if let lastPlayedDateForItem1 = item1.lastPlayedDate,
let lastPlayedDateForItem2 = item2.lastPlayedDate {
return lastPlayedDateForItem1.compare(lastPlayedDateForItem2) == .OrderedDescending
}
return false
}
}
Upvotes: 3