Add image url parsed from JSON API into UIImageView

323 Views Asked by At

I've parsed JSON API file into swift for nowplaying data of my radio. Now I'm able to display artist and song title in the two labels (Still looking how to fetch new data from API, when new song is playing - now the app shows static artist and title, so I need to reopen the app to see update). What I'm trying to do is to display image from artURL into UIMageView with aspect to fill mode. Here is my code:

import UIKit
import AVKit
import MediaPlayer

class ViewController: UIViewController, AVAudioPlayerDelegate {
    
    var player : AVPlayer!
    var dict = NSDictionary()
    var isPlaying = false
    let playImage = UIImage(named: "play.png")
    let pauseImage = UIImage(named: "pause.png")
    
    @IBOutlet weak var artist: UILabel!
    @IBOutlet weak var songtitle: UILabel!
    
    .......
    
    override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
            overrideUserInterfaceStyle = .light
            setupRemoteCommandCenter()
            //Radio API endpoint
            let urlString = "https://radioapp.com/api/nowplaying/radioapp"
            let url = URL(string: urlString)!
            let session = URLSession.shared
            let dataTask = session.dataTask(with: url) { data, response, error in
                if let error = error {
                    print(error)
                    return
                }
                guard let data = data else {
                    print("data is nil")
                    return
                }
                let decoder = JSONDecoder()
                do {
                    let radio = try decoder.decode(RadioAPI.self, from: data)
                    print(radio)
                    DispatchQueue.main.async {
                        self.songtitle.text = radio.nowPlaying.song.title
                        self.artist.text = radio.nowPlaying.song.artist
                        if let artUrl = URL(string: radio.nowPlaying.song.art) {
                         //Here I need to load an image from `artUrl`
                        }
                    }
                } catch {
                    print("Error Parsing JSON: \(error)")
                }
            }
            dataTask.resume()
        }

EDIT: My only idea is to add this, but still it does not work:

if let artUrl = URL(string: radio.nowPlaying.song.art) {
                            //I need to load an image from `artUrl`
                            let albumArt = UIImage(data: data)
                            let albumArtView = UIImageView(image: albumArt)
                        }
0

There are 0 best solutions below