// Given a track, attempts to fetch the lyrics from lyricswiki
class LyricsEngine {
+ private let clientToken = "_-P6qiz2dPDMaRUih-VxSS--PBYA4OtWrHiTgVY7Qd3lMss_oewL04FX8lmh37ma"
+
// URL of the API endpoint to use
- private let apiURL = "https://lyrics.wikia.com/api.php?action=lyrics&func=getSong&fmt=realjson"
+ private let apiURL = "https://api.genius.com/search"
// Method used to call the API
private let apiMethod = "GET"
if let artist = track.artist.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
if let name: String = track.name.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
- if let url = URL(string: "\(apiURL)&artist=\(artist)&song=\(name)") {
+ if let url = URL(string: "\(apiURL)&q=\(artist) \(name)") {
// We'll lock until the async call is finished
// Call the API and unlock when you're done
- fetchLyricsFromAPI(withURL: url, completionHandler: {lyricsResult -> Void in
+ searchLyricsUsingAPI(withURL: url, completionHandler: {lyricsResult -> Void in
lyrics = lyricsResult
requestFinished = true
asyncLock.signal()
// Fetch the lyrics URL from the API, triggers the request to fetch the
// lyrics page
- private func fetchLyricsFromAPI(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
+ private func searchLyricsUsingAPI(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
var apiRequest = URLRequest(url: url)
apiRequest.httpMethod = "GET"
if let data = data {
if let jsonResponse = try? JSONSerialization.jsonObject(with: data) {
if let jsonResponse = jsonResponse as? [String: Any] {
- if let lyricsUrlString = jsonResponse["url"] as? String {
- if let lyricsUrl = URL(string: lyricsUrlString) {
-
- // At this point we have a valid wiki url
- self.fetchLyricsFromPage(withURL: lyricsUrl, completionHandler: completionHandler)
- return
+ if let hits = jsonResponse["hits"] as? [Any] {
+ if let firstHit = hits[0] as? [String: Any] {
+ if let firstHitData = firstHit["result"] as? [String: Any] {
+ if let lyricsUrlString = firstHitData["url"] as? String {
+ if let lyricsUrl = URL(string: lyricsUrlString) {
+
+ // At this point we have a valid wiki url
+ self.fetchLyricsFromPage(withURL: lyricsUrl, completionHandler: completionHandler)
+ return
+ }
+ }
+ }
}
}
}