Skip to content

Commit

Permalink
feat: improve track image search
Browse files Browse the repository at this point in the history
  • Loading branch information
angristan committed Jul 8, 2021
1 parent d451b2a commit b69e0a5
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 4 deletions.
6 changes: 6 additions & 0 deletions firstfm/Data/Entities/Artist.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,9 @@ struct Artist: Codable, Identifiable {
var listeners: String
var image: [LastFMImage]
}

struct ScrobbledArtist: Codable {
let mbid: String
// let image: [LastFMImage]
let name: String?
}
4 changes: 3 additions & 1 deletion firstfm/Data/Entities/Track.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ struct ScrobbledTrack: Codable, Identifiable {
var name: String
var url: String
var image: [LastFMImage]
let date: LastFMDate
var artist: ScrobbledArtist
var loved: String?
let date: LastFMDate?
}

struct LastFMDate: Codable {
Expand Down
6 changes: 3 additions & 3 deletions firstfm/Data/ViewModel/ScrobblesViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ class ScrobblesViewModel: ObservableObject {

for (index, track) in jsonResponse.recentTracks.track.enumerated() {
// Get image URL for each track and trigger a View update through the observed object
self.getImageForTrack(trackName: track.name) { imageURL in
self.getImageForTrack(trackName: track.name, artistName: track.artist.name ?? "") { imageURL in
if let imageURL = imageURL {
DispatchQueue.main.async {
self.scrobbles[index].image[0].url = imageURL
Expand All @@ -87,8 +87,8 @@ class ScrobblesViewModel: ObservableObject {
}.resume()
}

func getImageForTrack(trackName: String, completion: @escaping (String?) -> ()) {
if let encodedTrackName = trackName.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
func getImageForTrack(trackName: String, artistName: String, completion: @escaping (String?) -> ()) {
if let encodedTrackName = "\(trackName) \(artistName)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
let queryURLString = "https://api.spotify.com/v1/search?q=\(encodedTrackName)&type=track&limit=1"
if let queryURL = URL(string: queryURLString) {
var request = URLRequest(url: queryURL)
Expand Down

0 comments on commit b69e0a5

Please sign in to comment.