2017-04-16 6 views
0

음악 앱에서 노래가 언제 재생되는지 알고 싶습니다. 하지만 라이브러리에서 모든 노래를 가져오고 싶지는 않습니다. 앱이 스캔을 시작한 이후로 재생 된 노래 일뿐입니다.신속하게 재생 된 노래를 얻는 방법

무언가를하는 것처럼 응용 프로그램을 열고 연주 한 내용을 스캔합니다.

나는 이것에 대해 조사했지만 아무 것도 발견하지 못했으며, 이것을 구현하기 위해 어디서부터 시작해야할지 모른다.

답변

1

먼저

그런 다음 당신은 다음 코드를 사용하여 일정 시간 이후 연주 된 모든 곡을 찾을 수 있습니다 사용자의 미디어 라이브러리에 액세스해야하는 이유에 대한 설명으로 Info.plistNSAppleMusicUsageDescription 키를 추가 :

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이 있지만 기기에서 테스트하는 것이 더 쉽습니다.

+0

완벽하게 작동하지만 문제가 있습니다. 한 번 이상 노래를 연주하면 결과 배열에 그 노래가 한 번만 포함됩니다. –

관련 문제