ICloud for Developers

Download ICloud for Developers

Post on 14-Oct-2015




0 download

Embed Size (px)


it is very useful


<ul><li><p>www.it-ebooks.info</p></li><li><p>www.it-ebooks.info</p></li><li><p>Early Praise for iCloud for Developers</p><p>Cesare does an excellent job demonstrating how iCloud works and how you canwork best within its expectations. His style is easy to follow, and he breaks itdown into simple steps, but he doesnt hold back and pretend that the complexityisnt there. Youll be building useful apps on iCloud in no time. Dont hesitate tobuy this book.</p><p> Jonathan Penn, http://cocoamanifest.net/</p><p>iCloud for Developers guides you through the three core features of iCloud: key-value store, documents, and CoreData. Each section has great examples to helpyou learn how to use the feature to its full potential. Buy this book if you want tolearn about iCloud!</p><p> Matt Galloway</p><p>The cloud can be a confusing topic, but Cesare makes it easy. He shows you howto add iCloud into a real app step-by-step, covering all the juicy bits youll wantto know along the way. If you want to use iCloud in your apps, this is the bookfor you!</p><p> Ray Wenderlich, raywenderlich.com</p><p>www.it-ebooks.info</p></li><li><p>iCloud for DevelopersAutomatically Sync Your iOS Data,</p><p>Everywhere, All the Time</p><p>Cesare Rocchi</p><p>The Pragmatic BookshelfDallas, Texas Raleigh, North Carolina</p><p>www.it-ebooks.info</p></li><li><p>Many of the designations used by manufacturers and sellers to distinguish their productsare claimed as trademarks. Where those designations appear in this book, and The PragmaticProgrammers, LLC was aware of a trademark claim, the designations have been printed ininitial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer,Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trade-marks of The Pragmatic Programmers, LLC.</p><p>Every precaution was taken in the preparation of this book. However, the publisher assumesno responsibility for errors or omissions, or for damages that may result from the use ofinformation (including program listings) contained herein.</p><p>Our Pragmatic courses, workshops, and other products can help you and your team createbetter software and have more fun. For more information, as well as the latest Pragmatictitles, please visit us at http://pragprog.com.</p><p>The team that produced this book includes:</p><p>John Osborn (editor)Kim Wimpsett (copyeditor)David J Kelly (typesetter)Janet Furlow (producer)Juliet Benda (rights)Ellie Callahan (support)</p><p>Copyright 2013 The Pragmatic Programmers, LLC.All rights reserved.</p><p>No part of this publication may be reproduced, stored in a retrieval system, ortransmitted, in any form, or by any means, electronic, mechanical, photocopying,recording, or otherwise, without the prior consent of the publisher.</p><p>Printed in the United States of America.ISBN-13: 978-1-937785-60-4Encoded using the finest acid-free high-entropy binary digits.Book version: P1.0July 2013</p><p>www.it-ebooks.info</p></li><li><p>Contents</p><p>Acknowledgments . . . . . . . . . . . vii</p><p>Preface . . . . . . . . . . . . . . ix</p><p>1. Preparing Your Application for iCloud . . . . . . . 1What Is iCloud? 21.1</p><p>1.2 Whats Behind iCloud 31.3 Introducing the Grocery Application 51.4 Enabling Your Application for iCloud 61.5 Checking for iCloud Availability 121.6 Moving On 13</p><p>2. Working with Key-Value Data . . . . . . . . 15iCloud Storage Types 152.1</p><p>2.2 Using Key-Value Pairs with iCloud 162.3 Using Key-Value Pairs in Grocery 172.4 Reacting to Changes in iCloud 212.5 Key-Value Storage Limitations 222.6 Moving On 23</p><p>3. Working with Documents . . . . . . . . . 25Interacting with iCloud 253.1</p><p>3.2 Extending the UIDocument Class 263.3 Modeling a Grocery Item as a UIDocument 303.4 Displaying a Grocery Item 323.5 Moving On 38</p><p>4. Managing Multiple Files and iCloud Notifications . . . . 39Creating and Managing Multiple Files 394.1</p><p>4.2 Creating and Managing Multiple Grocery Items 404.3 Managing Updates While an Application Is Running 45</p><p>www.it-ebooks.info</p></li><li><p>4.4 Editing Grocery Item Content 484.5 Moving On 53</p><p>5. Wrapping Items in a Single File . . . . . . . . 55Working with File Packages 565.1</p><p>5.2 Packaging Grocery Items 565.3 Updating the User Interface 645.4 Moving On 72</p><p>6. Handling Nontextual Information in a Data Model . . . 73Working with Data in Packages 736.1</p><p>6.2 Associating Images with Names 746.3 Updating the User Interface 806.4 Moving On 87</p><p>7. Handling Conflicts . . . . . . . . . . . 89Working with Document States and Notifications 897.1</p><p>7.2 Preventing Conflicts Between Grocery Items 917.3 Resolving Conflicts Between Grocery Items 967.4 Moving On 102</p><p>8. Working with Core Data and iCloud . . . . . . . 103The Relational Model of the Grocery List 1048.1</p><p>8.2 Initializing a Core Data Stack for iCloud 1068.3 Handling Conflicts 1148.4 Moving On 1178.5 Conclusion 117</p><p>A1. Bibliography . . . . . . . . . . . . 119</p><p>Contents vi</p><p>www.it-ebooks.info</p></li><li><p>AcknowledgmentsWhen a book shows just one author name on the cover, we tend to think itsthe result of a single-person effort. Thats far from the truth. Without the helpof the many people who surrounded me (though just virtually) during thewriting, this book would not have seen the light. I am happy to thank Andyand Dave for the opportunity to publish this book. John Osborn, the editor,deserves a special mention because he helped me throughout all the phasesof the writing, from organizing the content to tweaking obscure sentences.Finally, Id like to thank all the awesome technical reviewers who providedfeedback on all the chapters and the code attached to this book.</p><p> Jeff Holland Matt Galloway (http://www.galloway.me.uk) Felipe Laso Marsetti (http://ife.li/) Marcio Valenzuela (http://www.santiapps.com) Bear Cahill (http://www.brainwashinc.com) Tony Dahbura (http://www.fullmoonmanor.net/FullMoonManor/Welcome.html) Jonathan Penn (http://cocoamanifest.net)</p><p>report erratum discusswww.it-ebooks.info</p></li><li><p>PrefaceYou are an iOS developer with a successful application to your credit, butyour customers want more and pepper you with questions: How do I back upmy data? How can I replicate on my iPad the data that Ive created on myiPhone? If I buy a new iPhone, will I lose the data in my apps when I switchdevices?</p><p>Youd like to support your users, but you dont have the skills or time to builda back-end system that could provide the safe and reliable backups yourcustomers say they want. Moreover, the thought of synchronizing data acrossmultiple devices gives you a headache.</p><p>If any of this applies to you, iCloud is a good candidate for solving yourproblems and giving your users the features theyve requested. This book willteach you how to work with iCloud, hook up with its APIs, work with its dif-ferent storage solutions, and make your application shine.</p><p>Who Should Read This Book?</p><p>If you are an iOS developer looking to integrate your application with iCloudand to enhance it with data synchronization and backup, this book is for you.This book is also for those who simply want to know more about iCloud andthe features it provides to client applications.</p><p>Before digging in, you should already know the basics of programming iOS,including proficiency in coding with Objective-C 2.0, working with view con-trollers, and using common data structures such as arrays and dictionaries.If you dont normally use them, I also suggest you refresh your knowledge ofNotification Center1 and Grand Central Dispatch,2 both of which are usedextensively throughout the book.</p><p>1. https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Notifications/Introduction/introNo-tifications.html#//apple_ref/doc/uid/10000043-SW1</p><p>2. https://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html</p><p>report erratum discusswww.it-ebooks.info</p></li><li><p>Whats in This Book?</p><p>This book is an introduction to iCloud and how to use its APIs to add synchro-nization and data backup in your applications. Well cover the three maintechnologies that iCloud supports: key-value storage, document-based storage,and Core Data storage. I will illustrate the use of these APIs by showing howto build a Universal iOS app, Grocery, that keeps track of a shopping list.</p><p>How to Read This Book</p><p>The book starts with the simplest approach to synchronizing data with iCloud,key-value storage, and ends with the most advanced, Core Data. Unless youhave previous experience with iCloud APIs, I suggest you read the book fromstart to finish and take the time to understand the concepts and techniquesof iCloud development as they are introduced. Throughout the book, you willbe invited to build and run the Grocery application as it is being developed.You should consider these as conceptual check pointsopportunities toask yourself whether you have a clear understanding of whats been describedin the previous sections.</p><p>Notes on Formatting</p><p>Objective-C is a verbose language. You will find snippets in this book that donot appear to be conventionally formatted, in the way you would expect themto appear in Xcode. Thats because of the lengths of many of the names usedin iCloud programming, such as those for the various notifications the serviceprovides. Some of these are lengthy and cannot be broken on two differentlines. I have tried as much as possible to preserve Cocoa conventions, butsometimes the size of the page rules.</p><p>Online Resources</p><p>This book has a companion website at http://www.icloudfordevelopers.com and amailing list in which news will be announced.</p><p>Requirements</p><p>In this book we are going to build a real application. You will learn how to setit up and configure it correctly. But its not possible to test an iCloud-enabledapplication on the Device Simulator. This means that to get the most out ofthe book, youll need a pair of real devices, such as an iPhone and an iPad,both with iOS 6 installed and with iCloud correctly configured and enabled.</p><p>To test whether your devices are correctly configured for iCloud, fire up theApple-provided Calendar app, make an entry, and verify that synchronization</p><p>Preface x</p><p>report erratum discusswww.it-ebooks.info</p></li><li><p>happens correctly between the devices. Also access http://www.icloud.com to seewhether your entry has been propagated to the central iCloud servers.</p><p>To develop the application used throughout the book, you will need a Macwith Xcode 4.6.2 installed and updated to develop applications that targetiOS 6. We assume that you already have an active developer account and areacquainted with iOS development, Objective-C, Xcode, and Core Data. In caseyou need some introduction to iOS development, check out iOS SDKDevelopment [AD12] or find plenty of material at the iOS Dev Center:https://developer.apple.com/devcenter/ios/index.action.</p><p>Moving On</p><p>Now that you have all the pieces, lets get started. We are going to startslowly, by first introducing the basics of iCloud and showing you how to takeadvantage of its features in your application. To prepare for work on theGrocery app, youll also learn how to prepare the Xcode project for iCloud.Ready, set, go!</p><p>report erratum discuss</p><p>Moving On xi</p><p>www.it-ebooks.info</p></li><li><p>CHAPTER 1</p><p>Preparing Your Application for iCloudYou have created an attractive application that friends and families can useto jointly manage their shopping lists, to-do lists, and other types of lists.Your customers say they like it, but it lacks two features theyd like to see:backup and synchronization.</p><p>If you havent yet received such feedback, chances are you will. Apple usersexpect more from their applications these days because Calendar, Contacts,and many other Apple applications that ship with the latest iPhones, iPads,and Macs can both store their data in the cloud and sync it across multipledevices.</p><p>Take Calendar, Apples appointment application, for example. If you own twoor more Apple devicesan iPhone or iPad or twoand they all run iOS 6 orgreater, open Calendar on one of them and enter a new appointment for today.Now, switch to another device, open Calendar, and go to your entries fortoday. Provided that you have activated iCloud on both devices, youll findthe very same appointment on the second device that you just entered on thefirst.</p><p>Heres what happened. When you entered it, your iPhone or iPad pushed theappointment to servers operated by Apple. The Calendar application on thesecond device was listening for changes to the calendar, found yours, andupdated itself. Youll have the same experience whenever you enter a newcontact, save a photo, buy music, and more.1</p><p>1. For an overview of how Apple uses iCloud in its own applications, see http://www.apple.com/icloud/features/. The example of the Calendar app is used just to show a familiar scenariowhere data synchronization happens. Although I am not sure, it is likely the Calendarapp in iOS and Mac OS is not using iCloud API to synchronize.</p><p>report erratum discusswww.it-ebooks.info</p></li><li><p>Naturally, youd like to provide features like this to your own users. Fortunate-ly, Apple has not kept iCloud to itself but opened it to app developers like youand me. Now when you write an iOS application, youll be able to use theinformation in this book to add iCloud support that works on all of Applesdevices running iOS 5 or greater.2 Users who install the application on eachof their iOS devices will be able to store their data and keep it in sync. Andwe are talking about any kind of data: properties, configurations, documents,binary files, and even information in a relational database.</p><p>In this chapter, you will get acquainted with iCloud, learn how it works, andgo over the steps to take to prepare an app to use the service. Youll learnabout the following:</p><p> What iCloud provides and how you can take advantage of it</p><p> How iCloud handles data and synchronizes updates</p><p> How to prepare an iOS project for iCloud</p><p>We will also introduce and start work on Grocery, the application that weregoing to build together in this book to flex and show off iClouds features(Section 1.3, Introducing the Grocery Application, on page 5).</p><p>By the end of this chapter you will have a clearer idea of the scenarios iCloudsupports and the steps needed to start building an iCloud-enabled application.Lets begin by describing what iCloud does and how it works.</p><p>1.1 What Is iCloud?</p><p>iCloud is a cloud-based tool that can store data for an application at a centralserver and synchronize updates served up by the iPhones, iPads, or Macsthat use it. For both developers and users, iCloud solves two problems:backup and data synchronization.</p><p>For backup, data for an application need only be made to adhere to certainformats and specifications and stored in one or more special folders thatiCloud provides. For data synchronization, the application has to listen foriCloud notifications indicating changes have occurred and then, when one isreceived, resolve any conflicts that exist and update the local data store. Youwill learn to handle both cases in this book, but in order to understand howiCloud handles its data, you first need to understand how it works under thehood.</p><p>2. While its possible to add iCloud support to versions of your application that run ona Mac, we will not cover that topic in th...</p></li></ul>