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.
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"
Use this to get the duration of an MPMediaItem.
MPMediaItem *song;
NSNumber *duration= [song valueForProperty:MPMediaItemPropertyPlaybackDuration];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With