2011年11月21日星期一

iOS Code: MKiCloudSync – Sync your NSUserDefaults to iCloud with a single line of code

iOS Code: MKiCloudSync – Sync your NSUserDefaults to iCloud with a single line of code:
Just wrote this class, MKiCloudSync (100 lines of code) that auto syncs your NSUserDefaults to iCloud.

How to use?


All you need to do is to enable iCloud key value store entitlements, copy the files and forget about the rest.

Step 1:

Enable iCloud entitlements for your app. This is easily done in Xcode 4.2.1 by opening your target settings and checking “Enable Entitlements” from the summary tab.

This is illustrated below.

Xcode
Enabling iCloud Entitlements in Xcode 4.2.1


Tip:

If you are sharing settings with other apps, ensure that your iCloud Key-Value Store is the same across all those apps.

Step 2:

Drag the two files

  • MKiCloudSync.h
  • MKiCloudSync.m

into your project. You can find these files in the Source Code section of this post.

Step 3:

In your applicationDidFinishLaunchingWithOptions: method,

start the sync by calling,


[MKiCloudSync start];


You also have to #include the header file.

This is probably the only line of code you have to write!

Step 4:

Sleep… Kidding.

There is no step 4. Continue using NSUserDefaults to save your settings. The MKiCloudSync class automatically syncs your settings to iCloud and restores them back to your NSUserDefaults when they are changed on other devices.

To top them all, it also posts a notification,

kMKiCloudSyncNotification

to let you know that a sync has been performed. You can listen to this notification and update your user interface from NSUserDefaults.

Advantages


  • Upgrading your existing iOS 4 apps to sync settings to iCloud is now super easy.
  • With this class, you no longer have to add calls to NSUbiquitousKeyValueStore throughout your app. You can continue your existing method of saving them to NSUserDefaults. Everything is automatic. If your settings might change often, you can observe the notification kMKiCloudSyncNotification and update your user interface.

Source Code



Licensing


Royalty free for commercial or non-commercial use, though attribution will please me to write more such code :)



Mugunth
©2011 MKBlog. All Rights Reserved.

没有评论:

发表评论