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:

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
heightandwidthobject properties.Given your code above, and the fact that you're using a
Songtype object. The documentation here https://developer.apple.com/documentation/musickit/song alludes to the fact that aSongobject has an optionalartworkproperty of typeArtwork.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)