4 // Given a track, attempts to fetch the lyrics from lyricswiki
7 private let clientToken = <GENIUS_CLIENT_TOKEN>
9 // URL of the API endpoint to use
10 private let apiURL = "https://api.genius.com/search"
12 // Method used to call the API
13 private let apiMethod = "GET"
15 // The track we'll be looking for
16 private let track: Track
18 // Fetches the lyrics and returns if found
23 // Encode the track artist and name and finish building the API call URL
25 if let artist = track.artist.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
26 if let name = track.name.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
28 if let url = URL(string: "\(apiURL)?access_token=\(clientToken)&q=\(artist)%20\(name)") {
30 // We'll lock until the async call is finished
32 var requestFinished = false
33 let asyncLock = NSCondition()
36 // Call the API and unlock when you're done
38 searchLyricsUsingAPI(withURL: url, completionHandler: {lyricsResult -> Void in
40 requestFinished = true
44 while !requestFinished {
55 // Initializes with a track
56 init(withTrack targetTrack: Track) {
61 // Fetch the lyrics URL from the API, triggers the request to fetch the
63 private func searchLyricsUsingAPI(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
65 var apiRequest = URLRequest(url: url)
66 apiRequest.httpMethod = "GET"
68 let task = URLSession.shared.dataTask(with: apiRequest, completionHandler: {data, _, _ -> Void in
70 // If the response is parseable JSON, and has a url, we'll look for
71 // the lyrics in there
74 if let jsonResponse = try? JSONSerialization.jsonObject(with: data) {
75 if let jsonResponse = jsonResponse as? [String: Any] {
76 if let response = jsonResponse["response"] as? [String: Any] {
77 if let hits = response["hits"] as? [[String: Any]] {
78 let filteredHits = hits.filter { $0["type"] as? String == "song" }
79 if filteredHits.count > 0 {
80 let firstHit = hits[0]
81 if let firstHitData = firstHit["result"] as? [String: Any] {
82 if let lyricsUrlString = firstHitData["url"] as? String {
83 if let lyricsUrl = URL(string: lyricsUrlString) {
85 // At this point we have a valid wiki url
86 self.fetchLyricsFromPage(
88 completionHandler: completionHandler
101 completionHandler(nil)
106 // Fetch the lyrics from the page and send it to the parser
107 private func fetchLyricsFromPage(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
109 var pageRequest = URLRequest(url: url)
110 pageRequest.httpMethod = "GET"
112 let task = URLSession.shared.dataTask(with: pageRequest, completionHandler: {data, _, _ -> Void in
114 // If the response is parseable JSON, and has a url, we'll look for
115 // the lyrics in there
118 if let htmlBody = String(data: data, encoding: String.Encoding.utf8) {
119 self.parseHtmlBody(htmlBody, completionHandler: completionHandler)
124 completionHandler(nil)
129 // Parses the wiki to find the lyrics, decodes the lyrics object
130 private func parseHtmlBody(_ body: String, completionHandler: @escaping (String?) -> Void) {
133 let document: Document = try SwiftSoup.parse(body)
134 let lyricsBox = try document.select("div[data-lyrics-container=\"true\"]")
135 try lyricsBox.select("br").after("\\n")
136 let lyrics = try lyricsBox.text()
137 completionHandler(lyrics.replacingOccurrences(of: "\\n", with: "\r\n"))
139 completionHandler(nil)