Brave Location Mobile Apps and Web Solutions

Porting UserSettings code to Swift

Next stage of the app is to store the settings we previously added to both the local user settings and to iCloud for syncing across multiple devices.

Luckily I had some Objective-C code I could repurpose for most of the logic, but porting it was a useful exercise in getting used to the slightly obtuse casting syntax necessary in Swift when interacting with the frameworks.

Setting up iCloud preferences

To enable storing key-value pairs for the app in iCloud, it’s as simple as going to the Capabilities section of your project settings, and:

  1. Turn on the iCloud capabilities
  2. Make sure the “Key-value storage” checkbox is selected

Code to get and set preferences

The code - available on GitHub for viewing - is reasonably straightforward port of some common code I’ve used before.

I’ve refactored the main settings code into a BLUserSettings.swift class I should be able to reuse in other projects. The existing DaysLeftModel class now inherits from this base class, and the getters and setters have been changed to call the appropriate read/write methods in the base class.

The getters will read from the local user settings, so they’ll be available even if the device is offline. The setters will write to both the local store, and the cloud store, and the base class also handles notifications if the settings have been changed on a remote device, and writes them locally as appropriate.

Having a bunch of unit tests as always helped to test my refactoring of the model class worked fine.

Next steps

I think we’re now ready to start on the UI.

Previous posts in the series

The code for the project is also available on GitHub

N.B. This blog post has now moved to https://writingontablets.com