5

I wanna get song's listening times in a certain period. Using MPMediaItemPropertyLastPlayedDate I only get the date of the last time a song was played, so if a I play a song multiple times a day, only the last time will count. Basically, what I wanna do is getting user's listening history in a certain period (the last 2 days for example.) Also with MPMediaItemPropertyPlayCount I get the total play count overall.

Any ideas?

Thanks.

2 Answers2

2

I'm working with this right now. My (Swift code) is:

func getPlaysSince(since:NSDate, onSuccess: (tracks: [MediaItem])->(), onFail: (error: NSError?)->()) {

    var rValue = [MediaItem]()
    let timeInterval = since.timeIntervalSince1970
    let query = MPMediaQuery.songsQuery()
    let songs = query.items
    Logger.logMessage(domain: "Data", level: .Minor, "Checking \(songs.count) songs for those since \(since)")
    let then = NSDate()
    for song in songs {
        if let lastPlayedDate = song.lastPlayedDate {
            if lastPlayedDate != nil {
                if lastPlayedDate.timeIntervalSince1970 > timeInterval {
                    Logger.logMessage(domain: "Data", level: .Minor, "\(song.title) at \(lastPlayedDate)")
                    let item:MediaItem = MediaItem(mediaItem: song as! MPMediaItem)
                    rValue.append(item)
                }
            }
        }
    }
    let taken = NSDate().timeIntervalSinceDate(then)
    Logger.logMessage(domain: "Data", level: .Minor, "scanned in \(taken) seconds")

    onSuccess(tracks: rValue)

}

I've include my entire function, though the key lines are the assignments to query, songs and song, and then the check for lastPlayedDate. lastPlayedDate can be nil (never played this song before).

This code is doing a full check of my entire library 5K songs, and takes about 3 seconds. In my case I'm only interested in my play history since "since"

Derek Knight
  • 225
  • 2
  • 9
  • PS. Sorry I'm about a year late with this reply, but I've just started working on this today. You may have already figured out this for yourself. I didn't find many how-tos on the net, so this may still helps someone – Derek Knight May 24 '15 at 01:07
1

Use this to get the duration of an MPMediaItem.

MPMediaItem *song;
NSNumber *duration= [song valueForProperty:MPMediaItemPropertyPlaybackDuration];
Cody Robertson
  • 182
  • 2
  • 9