The online home of John Pollard

Updating code to watchOS 2

Updating my Count The Days Left app to watchOS 2 is clearly going to be more work than I thought :(

Upgrading to latest version of Swift

After loading the existing project into Xcode 7, it prompted me to update the Swift code, and when I accepted did a pretty good job of fixing everything up.

As a learning experience I reverted the changes to fix them up myself. Changes made included:

  • Changing the way string length is calculated e.g. count(self.model.title) => self.model.title.characters.count
  • Using generic Dictionary<String, AnyObject> where previous used NSDictionary
  • Updating NSCalendarUnit values e.g. NSCalendarUnit.CalendarUnitDay to NSCalendarUnit.Day
  • touchesBegan() event handler now has a Set<UITouch> parameter instead of a Set<NSObject> (and a ? on the event)
  • Lots of places I’d used var could be replaced by let - too much C# in the day job I suspect :)

Two versions of the shared library required

The big architecture change in watchOS 2 is that the watch extension code runs on the watch not the phone.

This should make the app much quicker, but brings in a whole raft of problems when migrating the code.

First up was making use of the shared library on code used by both the iOS app and the extension. The version running on the watch needs to be compiled against the watchOS SDK (obviously).

Getting this working stumped me for a while until I found this transition guide on the Apple developer site. See the Sharing Code Between an iOS App and a watchOS App section on how to make a duplicate library using the same files but compiling against the correct SDK.

Can’t share NSUserSettings any more

After solving the above problems, everything built and deployed to the simulator/phone/watch OK, but the watch app didn’t actually work. However a bit more reading of the upgrading code documentation pointed out a fundamental problem.

Because the extension has moved over to the watch, it doesn’t have access to the NSUserSettings objects, even if we’ve set up the App Groups capability correctly.

This means I’ll have to roll my own sharing of data between the app and the extension, which is a bit of a pain, but should be fun to learn.

More on how I get on next time!

N.B. All code can be seen on GitHub