最后听过的歌曲 (Swift)

Last heard songs (Swift)

我想用最后听过的歌曲填满 tableView。使用.nowPlayingItem我可以得到最后一首歌,但是我怎样才能得到以前听过的歌曲?

我认为这个问题已经在 Retrieve list of songs ordered by last play time in iOS 中有了答案,但它在 Objective-C 中,我无法翻译它。或者在 Swift 中有更好的方法吗?

这就是您在 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
    }
}

你可以这样做:

    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)

结果将存储在 sortedResults 数组中