0

So I implemented this code to get the song artwork from Apple Music based on what song the user searched for. However, the album cover is extremely blurry even when it is merely 50x50 in size. I can't figure out what is causing this issue.

  
import Foundation
import SwiftUI

class ArtworkLoader {
  private var dataTasks: [URLSessionDataTask] = []
  
  func loadArtwork(forSong song: Song, completion: @escaping((Image?) -> Void)) {
    guard let imageUrl = URL(string: song.artworkUrl) else {
      completion(nil)
      return
    }
    
    let dataTask = URLSession.shared.dataTask(with: imageUrl) { data, _, _ in
      guard let data = data, let artwork = UIImage(data: data) else {
        completion(nil)
        return
      }
      
      let image = Image(uiImage: artwork)
      completion(image)
    }
    dataTasks.append(dataTask)
    dataTask.resume()
  }

  func reset() {
    dataTasks.forEach { $0.cancel() }
    dataTasks.removeAll()
  }
}

Album cover sample after using code above:

album cover after using code above

Nexteon
  • 41
  • 6

2 Answers2

2

Based on the apple music API documentation available here (https://developer.apple.com/documentation/applemusicapi/artwork), you must specify the width and height that you want the API to return.

(Required) The URL to request the image asset. {w}x{h}must precede image filename, as placeholders for the width and height values as described above. For example, {w}x{h}bb.jpeg).

The artwork object will also tell you what the maximum width and height values available for the given artwork are, via the height and width object properties.

Given your code above, and the fact that you're using a Song type object. The documentation here https://developer.apple.com/documentation/musickit/song alludes to the fact that a Song object has an optional artwork property of type Artwork.

You can get the url for artwork image at a specific size by calling:

Song.artwork?.url(width: INSERT_WIDTH, height: INSERT_HEIGHT)

You can get the url for artwork image at its maximum size by calling:

Song.artwork?.url(width: Song.artwork?.maximumWidth ?? 0, height: Song.artwork?.maximumHeight ?? 0)

Brandon Stillitano
  • 1,304
  • 8
  • 27
0

Try using native solution. With SwiftUI, it becomes super simple -

if let artwork = mediaItem.artwork {
     ArtworkImage(artwork, width: 85) // or whatever width you need. 
         .cornerRadius(10)
}
Pankaj Gaikar
  • 2,357
  • 1
  • 23
  • 29