How to Display an Image Using WKInterfaceImage
(Originally published at FiveMinuteWatchKit.com, before the release of watchOS 2)
If you take a look at the class documentation for WKInterfaceImage, you’ll notice there are three different methods for displaying an image. For many developers new to WatchKit this has proven to be a bit confusing. When should you use one over the other? Where are the images coming from? Here’s a quick guide.
This method sends a UIImage — or multiple, if you’re creating an animation — from your WatchKit extension to your WatchKit app.
This method sends an NSData object containing one or more images from your WatchKit extension to your WatchKit app. This saves the overhead of creating a UIImage if you are trying to set an image with data loaded directly from a file or downloaded from the Internet.
If you have to send an image from the phone to the Watch, this is the most efficient way to do so.
This method displays an image that has already been stored in the WatchKit app’s bundle, or cached on the device. If you are trying to displaying an image from the bundle, be sure to specify the full name and the file extension.
If you are displaying an image using setImage: or setImageData: that you’ll show more than once, cache it using the addCachedImage:name: method on WKInterfaceDevice. Afterward, you can use the specified cache name when calling setImageNamed:.
Make sure to clear images out of the cache as needed — you get 20mb of storage and it isn’t pruned automatically. To remove an image from the cache, you can use the WKInterfaceDevice method removeCachedImageWithName:. To clear all cached images use removeAllCachedImages.
One thing to keep in mind: while Interface Builder will allow you to specify an image from anywhere in your project, it will only be displayed if it is included in your Watch app bundle.