Search code examples
iosswiftwatchkitapple-watch

Apple watch not showing any images


we are having problems with image not showing up on the apple watch, we tried the following :

Our image is located in the apple watchkit extension, and we tried to put it in the cache:

let img = UIImage(named:"slider_r.png")
WKInterfaceDevice().addCachedImage(img!, name:"slider_r.png")

It crashed immediately...

Then we tried to add the image directly on the apple watchkit app: no assets. No image loaded up...

Then we tried putting it in an image.assets didn't work either... We are currently out of ideas...

Thanks !


Solution

  • Alright, I've been working with WatchKit for about a month now - here's what I know:

    1. Placing your image into the Watch App's Assets Catalog will add it to the Watch's bundle. This will be immediately available for use using UIImage's .setImageNamed("name").
    2. Placing your image into the Watch Extension's Assets Catalog will add it to the extension's bundle, residing on the phone. Now, to get that to the watch you have to first grab a reference to the image from the extension, then add it to the device's cache, using WKInterfaceDevice().addCachedImage(image, name:).

    Check out the Apple documentation for providing images to the Watch here. Here's the documentation for setImage(_ image: UIImage?):

    This method changes the image being displayed. Use this method to send images from your WatchKit extension to the WatchKit app. The image interface object is resized to accommodate the size of the newly specified image. If the image itself is too large for the device’s screen, the image is clipped.

    This is not what you want. You want to explicitly add the image to the cache so you can use it later. If you use setImage as described above, it will transfer the image from the phone to the watch every time you call it, which is not ideal if you're using the same image in multiple locations or you're using it very frequently. You have to be careful in choosing exactly which images you want to cache on the watch.

    Using what we now know:

    var img: UIImage = UIImage(named: "slider_r") // grabs the image from extension's bundle
    WKInterfaceDevice().addCachedImage(img!, named: "slider_r") // adds to the Watch cache
    
    myImageOutlet.setImageNamed("slider_r") // grabs the image from the Watch cache
    
    • Ensure that the asset catalog is included in the extension's target so that the images are correctly placed in the bundle at runtime.
    • You do not need to include the extension (e.g. ".png") in the image's name.