Search code examples
swiftiboutlet

Dynamic IBOutlet to display Image


I am trying to set IBoutlet to display current playing album art. This is what I have so far but no dice.

@IBOutlet weak var nowPlayingArtBackground: UIImageView!

    func currentArt() -> UIImage? {
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    @IBOutlet = currentArt()

Solution

  • There's some things in your code - particularly @IBOutlet = currentArt() that makes it hard to understand how you think the code will work. So let's try starting at a high level.

    You need a UIImageView (we'll call it nowPlayingArtBackground) that will display a piece of artwork (say, the output of a function called currentArt). SO far, so good with what you have. Using @IBOutlet suggests you're setting this all up in a Storyboard - good.

    If you want the output of currentArt() to be viewed in nowPlayingArtBackground, the line of code you want is:

    nowPlayingArtBackground.image = currentArt()
    

    This will take the output from your function and display it. But there's two questions you haven't really answered:

    (1) Where is the output from currentArt() coming from?

    Your function code is code taking the contents of a UIGraphicsGetImageFromCurrentImageContext(), but exactly what is this context? Generally speaking, album artwork is stored someplace, be it a database (Firebase?) or a file (locally? cloud?) - as it is, you haven't necessarily defined this.

    (2) What triggers changing the artwork displayed?

    In other words, what triggers a call to currentArt().

    Let's say you have your artwork stored locally as data in a database with the key being song/artist. You need a "driver" probably some AV stream (I'm really no expert on audio, but I only mean it's the "music player" that needs to drive things). When the song changes, you need to set the image to be the output of currentArt(), and you need to properly code the function to call up the artwork for that song/artist combination.

    Hopefully some of this get you pointed in the right direction - or at least shows you some of the things missing in your question. Good luck!