Search code examples
swift3uiimageviewcocoapodstvos

tvOS: asset works when used in interface builder, but not programmatically


So I'm running into a weird issue. I'm adding to an existing project started by another developer which already has assets that work perfectly fine.

I added a few new image assets and when I reference them by name in the interface builder (when placing a UIImageView) they work perfectly fine, however when I try and create a UIImage with the same name, it always returns nil.

let myImage = UIImage(named: "my-image-name") // Always returns nil

I've ensured it has the proper target, that I have no typos, etc, but it just doesn't seem to work. For some extra info this is in a local development pod that I'm making changes to.


Solution

  • is the asset in your main application bundle or is it, on the other hand, in one of this local development pods that you mentioned at the end?

    As you can see in UIImage documentation: https://developer.apple.com/reference/uikit/uiimage/1624154-init

    UIImage initializer has a second parameter in to indicate the bundle in which the asset is actually defined, having the main application bundle as a defaults value.

    It means that if your asset "my-image-name" is not defined in the main bundle it will not be found.

    If you are trying to load the asset from the same bundle in with it is defined, you could load it with the following code:

    let image = UIImage(named: "my-image-name", in: Bundle(for: self))
    

    On the other hand, if you are trying to load the asset from a different bundle, you have to indicate the bundle.

    let image = UIImage(named: "my-image-name", in: Bundle(forClass: CLASSINYOURLOCALFRAMEWORK.self))