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? [Any] {
78 if let firstHit = hits[0] as? [String: Any] {
79 if let firstHitData = firstHit["result"] as? [String: Any] {
80 if let lyricsUrlString = firstHitData["url"] as? String {
81 if let lyricsUrl = URL(string: lyricsUrlString) {
83 // At this point we have a valid wiki url
84 self.fetchLyricsFromPage(
86 completionHandler: completionHandler
99 completionHandler(nil)
104 // Fetch the lyrics from the page and send it to the parser
105 private func fetchLyricsFromPage(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
107 var pageRequest = URLRequest(url: url)
108 pageRequest.httpMethod = "GET"
110 let task = URLSession.shared.dataTask(with: pageRequest, completionHandler: {data, _, _ -> Void in
112 // If the response is parseable JSON, and has a url, we'll look for
113 // the lyrics in there
116 if let htmlBody = String(data: data, encoding: String.Encoding.utf8) {
117 self.parseHtmlBody(htmlBody, completionHandler: completionHandler)
122 completionHandler(nil)
127 // Parses the wiki to find the lyrics, decodes the lyrics object
128 private func parseHtmlBody(_ body: String, completionHandler: @escaping (String?) -> Void) {
131 let document: Document = try SwiftSoup.parse(body)
132 let lyricsBox = try document.select("div[data-lyrics-container=\"true\"]")
133 try lyricsBox.select("br").after("\\n")
134 let lyrics = try lyricsBox.text()
135 completionHandler(lyrics.replacingOccurrences(of: "\\n", with: "\r\n"))
137 completionHandler(nil)