Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

iCloud with MonoTouch


Published on

Video for this session:

Code for this session:

Give your feedback on the session:

Craig Dunn walks us through using iCloud features in your MonoTouch apps, using different techniques such as iCloud Key-Value Storage and iCloud Document Storage.

Published in: Technology, Business
  • Be the first to comment

iCloud with MonoTouch

  1. 1. Xamarin Seminar 22nd March 2012 Copyright 2012 © Xamarin Inc. All rights reserved
  2. 2. Announcements Xamarin Copyright 2012 © Xamarin Inc. All rights reserved
  3. 3. AgendaiCloud with MonoTouch Craig Dunn Technical Writer Xamarin Documentation Team Xamarin Copyright 2012 © Xamarin Inc. All rights reserved
  4. 4. IntroductionThis session discusses Apple’s new iOS5 iCloudfunctionality and how to implement iCloud featureswith MonoTouch.We’ll cover:• iCloud Basics & Setup• iCloud Key-Value Storage• iCloud Document Storage• iCloud Backup (iOS Data Storage Guidelines) Xamarin Copyright 2012 © Xamarin Inc. All rights reserved
  5. 5. iCloud Basics (i) • Remote storage & backup • Synchronization of data across devices (iOS & Mac OS X) but NOT conflict resolution • OS process controls sending/receiving CloudiPhone Local storage storage Local storage iCloud Daemon iCloud Daemon iCloud Daemon Mac Local storage iPad
  6. 6. iCloud Basics (ii)• 4 ways to utilize iCloud: • Key-Value Pairs today’s topic • UIDocument • CoreData another • Individual files/folders time...
  7. 7. iCloud Setup (i)• App ID & Provisioning Profile ( • grants iCloud support (tick the box!) • linked to your TeamID and the BundleID• Entitlements.plist (in your project) • specify TeamID & BundleID • use these keys:
  8. 8. iCloud Setup (iii)• MonoDevelop Entitlements UI with placeholder expansion: • $(TeamPrefixIdentifier) automatically added • $(CFBundleIdentifier) for the default ubiquity-identifier han it E asier t ith l ooks, w lop! Mono Deve
  9. 9. iCloud Setup (iv)• Don’t forget the devices! • Same AppleID on each device
  10. 10. Key-Value Pairs (i)• Similar to NSUserDefaults• Simple types only (whatever works in a plist): text, number, date• Limited size: • 64Kb total • 64Kb max per key too• Recommendation: use NSUserDefaults and ‘shadow’ with iCloud Key-Value pairs
  11. 11. Key-Value Pairs (ii)Example creates a ‘key’ for each device, plus a Shared one.
  12. 12. Key-Value Pairs (iii)• SetString• GetString• Synchronize() returns false if no iCloud OR if no updates are required• Your app should run even if the Key-Values are empty! (sounds obvious, but...)
  13. 13. Key-Value Pairs (iv) • Change Notifications Register for notificationServerChangeInitialSyncChangeQuotaViolationChangeTells us which keys NSArray of IntPtrshave changed values Loop through the keys, get the new values and do something!
  14. 14. Files in the Cloud • NSFileCoordinator & NSFilePresenter work with the iCloud to prevent contention on the local copy • UIDocument hides that complexity from you! aka UbiquityContainer Cloud storage Presenter / Coordinator Local Presenter / Coordinator Local storage storageiPhone iCloud Daemon iCloud Daemon Mac Presenter / Coordinator iCloud Daemon or just use Local UIDocument! storage iPad
  15. 15. UbiquityContainer Ru ki Bloc backg a all! ng c round n on thread!• NSFileManager.DefaultManager.GetUrlForUbiquityContainer() • /private/var/mobile/Library/Mobile%20Documents/ AAA7MMJKYN~com~xamarin~samples~taskcloud/ Documents/ (user-visible in Settings) <your other stuff>• Not to be confused with your app’s home directory • /private/var/mobile/Applications/42871799- F2CD-455B-9353-749B15C8AA76/ (app bundle) Documents/ (user-visible in iTunes) Library/ <your other stuff>
  16. 16. UIDocument (spoilers)• Where are iCloud documents stored? UbiquityContainer Asyn c• How do you create a UIDoc? UIDoc.Save(ForCreating) Asyn c• How do you open one? UIDoc.Open() Asyn• How are changes applied? your model on the UIDoc) c (to• How do you save it again? UpdateChangeCount() UIDoc.• What if it changes elsewhere? for notification... Listen Asyn c• How do you enumerate NSMetadataQuery() Asyn c UIDocs? Asyn c
  17. 17. UIDocument (example)
  18. 18. Finding UbiquityContainerThis one line iskey to getting Asyn ciCloud working! Do this in FinishedLoading. Apple also recommends re-checking each time the app comes to the foreground.
  19. 19. Subclassing UIDocument• Override the ‘read’ and ‘write’ methods: • Actually called LoadFromContents() and ContentsForType()• iCloud takes care of when they’re called and manages contention at the file system level.• You NEVER read/write the filesystem directly! • Save(CompletionHandler) As ync hro no • Open(CompletionHandler) us! • UpdateChangeCount
  20. 20. Subclassing UIDocument url to UbiquityContainer location default value‘Model’ can beas simple orcomplex as youlike aka ‘Open’So we can respond to this datachanges if we want aka ‘Save’ accesses the model and sends to filesystem
  21. 21. Create a UIDocPut user-generated files inthe /Documents/ directory Has the ‘(default text)’ setSave happens Asynasynchronously, the ccompletion handler runswhen it is done • You could also use NSFileManager.DefaultManager.SetUbiquitous() to move an existing file from your home directory to the UbiquityContainer
  22. 22. Open UIDoc Open specific filenamefrom the /Documents/ directory Asyn c Might need to be run on Main thread
  23. 23. Changes Applied & SavedUpdateChangeCount() is Update the model withall that is required to the edited textsignal to iCloud that thefile should be saved* * You can implement full undo/redo instead of UIDocumentChangeKind.Done
  24. 24. Changes ElsewhereListen for notification sent bythe UIDocument subclasswhen it is changed When that notificationoccurs, we are grabbing theupdated text and assigning it to the UITextView ** In a real app, you would probably want to do someconflict resolution instead...
  25. 25. Enumerate UIDocs (i)CloudUIDoc exampleLooking for a single,specific filename Special Predicate syntax(monkeyDocFilename)TaskCloud example (just to show a different query) Looking for all Special Predicate syntax *.task files queryDidFinishGathering on next slide...
  26. 26. Enumerate UIDocs (ii)When the NSMetadataQuery is done,we stop it (it could keep running/monitoring) and remove our listener We expect only one file in theexample app; get its “ItemURL” thencreate and open the document from that location • Metadata sync’s faster, so other devices will learn if a particular file has been created (even though they don’t know the contents)
  27. 27. Debugging Tips (i)• The /Documents/ directory can be managed by the user (and you, for testing)
  28. 28. Debugging Tips (ii) • Check your iCloud-linked Mac, sync’d files will be there if everything is working correctly/Users/<you>/Library/Mobile Documents/<TeamId><BundleId>/Documents
  29. 29. iOS Data StorageGuidelines (for iCloud)• Only documents that are user-generated should go into /Documents/• Data that can be re-created should go into /Library/Caches/• Temp data should be in /tmp/• Use the “do not backup” attribute to prevent ANY files being backed-up to iCloud
  30. 30. Other examples• Key-Value ~ chat2self
  31. 31. Other examples• UIDocument ~ TaskCloud
  32. 32. References (i)Introduction to iOS 5 (currently being updated)’s New in iOS - iCloud UIDocument sample - iCloud Key-Value sample Data Storage Guidelines Xamarin Copyright 2012 © Xamarin Inc. All rights reserved
  33. 33. References (ii)NSFilePresenter Protocol Reference Class Reference Developer Documentation Xamarin Copyright 2012 © Xamarin Inc. All rights reserved
  34. 34. Xamarin Seminar Please give us your feedback Follow us on Twitter @XamarinHQ 22nd March 2012 Copyright 2012 © Xamarin Inc. All rights reserved