Lev Walkin (lionet) wrote,
Lev Walkin

Swift, Apple Watch, and Dynamic Graphs

To Hacker News fellas: please recognize the phrase about a week worth of battery is just a joke. Today I learned that even HN trolls don't understand a concept of trolling. Read into the technical side of this writeup, ignore opinions.

I tried to write something for Apple Watch as a weekend project to polish my rough Swift skills. Swift got me rather excited. It takes some things from OCaml and FP, having a strong nod to immutability concerns. Constants are defined via let, and variable are allowed to vary through a var. Though constants are lame, as only the binding itself is constant and you can change everything inside them as usual.

Nevertheless, Swift is a step in right direction. I enjoyed programming for the most part. However, XCode was traditionally nauseous with its hiccups and interventions into my editing process.

I made an app which shows a dynamic 30fps graph inside the Watch Emulator. Incidentally, had to figure out how to made the animated gifs use solid colors, rather than being hellishly dithered. There's a two step process. First, you have to generate a single palette out of all frames. Then you apply that same palette in the second conversion. The overall workflow would look like this: use a standard QuickTime player to record a screencast, then filter that .MOV through this script to get a .GIF.

The Watch App sources are here: https://github.com/vlm/ExampleWatchGraph (look for WatchKit Extension — that's the very part that runs on a Watch).

The Watch SDK has a strong Apple-style feel, if you get my french. For example, in order to draw something dynamic on a screen, you have to do the following 30 times a second:
  1. Create a graphics context using a size known in advance. You can't just get the WKInterfaceImage dimensions, that'd be too easy. You can only set the user interface element size, not get it.
  2. Draw what's needed through a CoreGraphics (Quartz 2D, runs on a CPU) — that seems to be the easy part.
  3. Convert the context into a .PNG and assign that .PNG to the WKInterfaceImage. Check this out: https://github.com/vlm/ExampleWatchGraph/blob/master/ExampleWatchGraph%20WatchKit%20Extension/GraphPainter.swift#L117

In the end of the day, the watch battery is there just to shuffle these .PNGs around. When Apple realizes how to avoid that, the watch will last for a week instead of hours.

Here's my profiling session showing this .PNG madness:

  • Post a new comment


    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded