먼저
그런 다음 당신은 다음 코드를 사용하여 일정 시간 이후 연주 된 모든 곡을 찾을 수 있습니다 사용자의 미디어 라이브러리에 액세스해야하는 이유에 대한 설명으로 Info.plist
에 NSAppleMusicUsageDescription
키를 추가 :
를
import MediaPlayer
@IBAction func getSongs(_ sender: Any) {
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Calendar.current.startOfDay(for: Date()))!
// Check for permissions
switch MPMediaLibrary.authorizationStatus() {
case .authorized, .restricted:
fetchSongPlayed(since: yesterday)
case .notDetermined:
MPMediaLibrary.requestAuthorization { _ in
let auth = MPMediaLibrary.authorizationStatus()
if auth == .authorized || auth == .restricted {
self.fetchSongPlayed(since: yesterday)
}
}
case .denied:
print("No access to the Media Library")
}
}
func fetchSongPlayed(since date: Date) {
let query = MPMediaQuery.songs()
var results = [MPMediaItem]()
if let songs = query.items {
results = songs.filter { ($0.lastPlayedDate ?? Date.distantPast) > date }
} else {
print("Can't fetch songs")
}
// Now do whatever you want with results
// It's an array of MPMediaItem
print(results.count)
}
한 가지 더 팁 : 시뮬레이터에 별다른 오류가 없으므로 iTunes에서 일부 음악을 iTunes에 동기화하십시오. 시뮬레이터에 a way to add it이 있지만 기기에서 테스트하는 것이 더 쉽습니다.
완벽하게 작동하지만 문제가 있습니다. 한 번 이상 노래를 연주하면 결과 배열에 그 노래가 한 번만 포함됩니다. –