Skip to content

Stop Watching Me!

Apple made an awesome piece of hardware. It’s called Apple Watch. Wouldn’t it be cool if we could make some code and try to control that device? Sure. Let’s do it.

If you haven’t done this already – make sure to download Xcode from Apple Developer website.

Create a New project, choose watchOS templates and click on iOS App With WatchKit App in Application category. Name the project: Animals.

Let’s tackle our UI first. Go to AnimalsWatch folder and open Interface.storyboard. You will see Apple Watch as Interface Controller scene. From object library, drag WKInterfaceImage and bellow it, put WKInterfaceButton. Rename the button label to Show Animal.

Your final screen should look like this:

After our UI, finally, it’s time for some code.

Open AnimalsWatch Extension folder and open InterfaceController.swift.

First, let’s define our image so we can ‘talk’ to it.

Next, we need an action which we will grab the image after the user taps on our button.

We defined a new function, grabImage() which will grab our image and present it to the end user.

Now hold on for a second…

On iOS, we have an UIImageView. On watchOS we have a WKInterfaceImage. Strange thing is that we cannot set our image in those two controls via URL. Should we take some third-party API in order to do that? Of course not.

Let’s build our own extension and don’t violate DIY principle (Do It Yourself).

I think that code is more or less self-explanatory. We detach from main thread, to avoid some UI glitches, we grab our bag of bytes from the URL and if everything is ok – we transform those bytes to an actual image.

With extension, we kind of tell to Apple – ‘I think you didn’t make those controls very good, I will extend them. This is how they should be made’ 🙂

So finally, let’s write our grabImage() function:

Wow! Is really that simple? Absolutely.

Look at the final results:

Of course, we hardcoded some image. But there is some nice free API’s where you get a random image on every request to the server. One of them is: PlaceIMG.

I’ll leave that to you, so you could update our watchOS app 😉

Of course, code is available on Github.

Happy coding!

Published iniOSTutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: