🌈 ESP32-S3 Rainbow: ZX Spectrum Emulator Board! Get it on Crowd Supply →
View All Posts
read
Want to keep up to date with the latest posts and videos? Subscribe to the newsletter
HELP SUPPORT MY WORK: If you're feeling flush then please stop by Patreon Or you can make a one off donation via ko-fi

The new version of Sudoku Grab is going to be a universal app (iPhone and iPad) so it’s become even more important that user data sync across all the devices an user owns.

The types of data that we need to sync are: settings (colours, fonts etc..) and puzzle data. In this post I’m going to talk about settings and persisting settings in the cloud.

The mechanism that Apple recommends for doing this is the NSUbiquitousKeyValueStore and there is some pretty decent documentation on how to get it up and running in the Storing Preferences in iCloud document.

There’s a couple of thing to be aware of - the Key-Value data store is intended for small amounts of data:

The total space available in your app’s iCloud key-value storage is 1 MB per user. The maximum number of keys you can specify is 1024, and the size limit for each value associated with a key is 1 MB. For example, if you store a single large value of exactly 1 MB for a single key, that fully consumes your quota for a given user of your app. If you store 1 KB of data for each key, you can use 1,000 key-value pairs.

And:

The maximum length for a key string is 64 bytes using UTF8 encoding. The data size of your cumulative key strings does not count against your 1 MB total quota for iCloud key-value storage; rather, your key strings (which at maximum consume 64 KB) count against a user’s total iCloud allotment.

If you think you are going to be storing more than that amount of data then the key-value store is not for you and it’s probably worth asking yourself if you are really storing user defaults or some other kind of data.

Setting up for iCloud key-value store

The first thing to do is to enable your app for cloud synching. There seem to be too places where this needs to be done and I’m not sure if the xcode step also does the dev portal step - so I’d recommend doing both…

When you create your app Id you’ll need to switch on the iCloud App Services option - if you are updating an existing app then enabled the iCloud App Services and then I’d suggest regenerating your provisioning profile.

'Setup App ID for iCloud'

Now create/open your app select your target and modify the Capabilities section enabling iCloud and make sure you tick the ā€œUse key-value storeā€ checkbox. 'Setup project for iCloud'

Getting values from iCloud

You’re now ready to go! To use your iCloud settings you’ll need to get hold of the default NSUbiquitousKeyValueStore (this code is take from the Preferences and Settings Programming Guide).

NSUbiquitousKeyValueStore* store = [NSUbiquitousKeyValueStore defaultStore];
[[NSNotificationCenter defaultCenter] addObserver:self
          selector:@selector(updateKVStoreItems:)
          name:NSUbiquitousKeyValueStoreDidChangeExternallyNotification
          object:store];
[store synchronize];

This code gets hold of the default store and registers us to get updates when something changes in the store (e.g. another device modifies the values). We then synchronize the store with the cloud.

You should run this code as soon as possible when your app launches so that you get any changes immediately - you respond to these changes in the updateKVStoreItems notification:

- (void)updateKVStoreItems:(NSNotification*)notification {
   // Get the list of keys that changed.
   NSDictionary* userInfo = [notification userInfo];
   NSNumber* reasonForChange = [userInfo objectForKey:NSUbiquitousKeyValueStoreChangeReasonKey];
 
   // If a reason could not be determined, do not update anything.
   if (!reasonForChange)
      return;
 
   // Update only for changes from the server.
   NSInteger reason = [reasonForChange integerValue];
   if ((reason == NSUbiquitousKeyValueStoreServerChange) ||
         (reason == NSUbiquitousKeyValueStoreInitialSyncChange)) {
      // If something is changing externally, get the changes
      NSArray* changedKeys = [userInfo objectForKey:NSUbiquitousKeyValueStoreChangedKeysKey];
      // do whatever you need to do when settings change
   }
}

There are three possible reasons for receiving a change notification:

  • NSUbiquitousKeyValueStoreServerChange - another device updated the values in iCloud.
  • NSUbiquitousKeyValueStoreInitialSyncChange - slightly more complicated, only happens under these circumstances:
    1. You start the app and call synchronize
    2. Before iOS has chance to pull down the latest values from iCloud you make some changes.
    3. iOS gets the changes from iCloud
  • NSUbiquitousKeyValueStoreQuotaViolationChange - you’re using it wrong and trying to store too much data.
  • NSUbiquitousKeyValueStoreAccountChange - the user has changed to a difference iCloud account. What you should probably do is clear down the user defaults to their default settings and then copy accross any new values from the cloud.

Storing values in iCloud

You can treat the NSUbiquitousKeyValueStore just as you would NSUserDefaults:

[[NSUbiquitousKeyValueStore defaultStore] setString:@"Mr Blobby" forKey:@"name"];
[[NSUbiquitousKeyValueStore defaultStore] synchronize];

As with NSUserDefaults it’s not neccessary to call synchronize every time you make a change (but calling synchronize will cause any changes to be sent to iCloud immediately).

Off line or No iCloud account

From my expeiments on my test devices if you are offline or if you have no iCloud account then values are still persisted - so it seems like these edge cases are not something to worry about.

Demo Project

I’ve put a very simple demo project up on github. Make sure you modifiy the app id to one that you have created on your own account and modified the code signing and provisioning profile settings.

Related Posts

Updating Sudoku Grab - Currently, I am revitalizing Sudoku Grab, my first app ever, published in 2009. The plan involves updating the code, upgrading to ARC, simplifying the menu system, accommodating iOS7, and supporting 4-inch display sizes. Future updates may include iCloud syncing features for universal access to puzzles. This endeavor also gives me an excuse to switch to an iPhone5s!
Version 2 of SudokuGrab released - We've updated SudokuGrab with some major enhancements including iCloud syncing for your puzzles and support for iPads. There are a few bugs we're aware of and we're actively working to fix them in the coming weeks, with a new version already submitted to the app store.
25000 copies downloaded! - I'm thrilled to announce that Sudoku Grab has reached 25000 downloads! As a token of gratitude, the app will be available for free until the 25th June. A huge thank you to everyone who has purchased the app and for all the valuable feedback.
Sorry for the long silence... - Haven't been around for a while, folks! Been keeping busy with a startup and working on a server-side project for www.vollow.me. Time to dust off those old Java and database abilities! Soon, I'll be getting my hands on building the app to go with the website. Keep your eyes peeled for some insightful iPhone-related posts coming your way!
Shoot3D for the iPad/iPhone - I'm thrilled to have introduced my first 3D game on the app store. The entire process served as a real learning curve, with some elements still appearing obscure, yet adding to the intrigue. The games section of the app store is known for its fierce competition, but challenging the status quo by doing something different from the regular utility apps is quite a welcome change. I'm generally proud of how the game has turned out and look forward to its reception. You can download the game on the app store.

Related Videos

M5Stack CORE2 - Can't remember why I got this, but it looks nice! - Hey guys! So today, I'm testing out this really cool app. It's pretty interesting - I think it could be really handy if you're into tech stuff. Let's dive in and see what it can do!
Is it time to change my batteries? Amazon thinks so! - Got a heads up from Amazon that one of my device batteries was low. Gotta give it to the battery, it lasted quite longer than I anticipated. So, I peeked into the device usage history, which was a trove of data Amazon has kindly stored. In fact, I wrote a web scraper to download all this data. Sadly, records only go back to two weeks. Nevertheless, I plotted the data and surprisingly the pattern revealed that battery level gets affected by temperature change. Cool, isn't it? Finally managed to change the battery. Also, I might just plug in a rechargeable one next time so as to not be a part of the 'throw-away battery' culture. All in all, quite an interesting discovery, courtesy of my Amazon device battery.
ESP32-S3 - Which Pins Are Safe To Use? - In this video, I've decided to dive deep into the ESP32-S3, a module ruling my lab recently due to its plug-in-and-play functionality, and the flexibility offered by its GPIO matrix. However, working with it requires vigilance, especially with regard to the strapping pins and USB data pins, among others. Discovering such quirks, I've encountered unexpected values, short glitches and the occasional code crash. To help you avoid these bumps, I've documented everything I've learned on my GitHub repo, where I'm inviting you, my fellow makers and engineers, to contribute your valuable experiences and findings. After a minor hiccup with my ESP32-TV, expect an updated PCB design, courtesy of PCBWay. Explore the ESP32-S3 with me, and let's unravel its secrets together, one pull request at a time.
ESP32 - 40 Independent touch pins! - Wow! I'm absolutely thrilled with the results of this video - I've been experimenting with my ESP 320x Spectrum board and its touch Matrix keyboard. Had a bit of trouble with combined button inputs, so I took a deep dive into how touch works and discovered these old, but gold, ICs. After some testing, they turned out to be a perfect solution to my multiplexing problem! I then got a new board design shipped from PCB way - looks awesome and it didn't break the bank. Can't believe how responsive the keyboard is! Got the 'Hello World' program up and running, and even played Manic Miner. The final board's all set - can't wait to get this on sale! And keep watching because I've got some interesting plans for this expansion port!
ESP32 SD Card Speedup With a Couple of Lines of Code - In this video, we explore the disappointingly slow data writing speed of the ESP32 when reading and writing to an SD card in our TinyTV project. With 500 kilobytes/sec reading and a dismal 270 kilobytes/sec writing, we embark on an adventure to find a solution. After ditching the Arduino code in favor of IDF functions, we discover incredible improvements. Seeing potential risks, I propose a truly bonkers plan: using a IC to interface SD cards with USB with a USB multiplexer switch and another switch to alternate between ESP32 and the GL823. This could be a total disaster, but I'm game for the challenge. Stay tuned to see if it works out!
HELP SUPPORT MY WORK: If you're feeling flush then please stop by Patreon Or you can make a one off donation via ko-fi
Want to keep up to date with the latest posts and videos? Subscribe to the newsletter
Blog Logo

Chris Greening


Published

> Image

atomic14

A collection of slightly mad projects, instructive/educational videos, and generally interesting stuff. Building projects around the Arduino and ESP32 platforms - we'll be exploring AI, Computer Vision, Audio, 3D Printing - it may get a bit eclectic...

View All Posts