Stanford CS193p. Developing Applications for ios. Fall Stanford CS193p. Fall 2011

Similar documents
What's new in ios 5?

Stanford CS193p. Developing Applications for ios. Fall Stanford CS193p. Fall 2011

Developing Applications for ios

Agenda. Core Data! Next Week! Storing your Model permanently in an object-oriented database.! Multitasking! Advanced Segueing! Map Kit?

App SandBox Directory

ios Mobile Development

Stanford CS193p. Developing Applications for ios. Fall Stanford CS193p. Fall 2011

Managed Object Model schema Persistent Store Coordinator connection Managed Object Context scratch pad

Stanford CS193p. Developing Applications for iphone 4, ipod Touch, & ipad Fall Stanford CS193p Fall 2010

Data IAP 2010 iphonedev.csail.mit.edu edward benson / Thursday, January 14, 2010

Introducing CloudKit. A how-to guide for icloud for your Apps. Frameworks #WWDC14. Session 208 Olivier Bonnet CloudKit Client Software

Managing Documents In Your ios Apps

Stanford CS193p. Developing Applications for ios Fall Stanford CS193p. Fall 2013

Settings. Mobile Application Development in ios School of EECS Washington State University Instructor: Larry Holder

Stanford CS193p. Developing Applications for ios. Fall Stanford CS193p. Fall 2011

Stanford CS193p. Developing Applications for ios Fall Stanford CS193p. Fall 2013

ITP 342 Mobile App Development. Data Persistence

CS193P - Lecture 16. iphone Application Development. Audio APIs Video Playback Displaying Web Content Settings

Objective-C. Stanford CS193p Fall 2013

CS193E Lecture 7. Document-based Applications NSTableView Key-Value Coding

Stanford CS193p. Developing Applications for ios. Fall CS193p. Fall

ITP 342 Advanced Mobile App Dev. Core Data

E Event-based parser, XML, 180 Extended attributes, URLs, 118 API, 119 command line, 118 description, 118 NSURL category, 119

Data Management

Stanford CS193p. Developing Applications for ios. Winter CS193p. Winter 2017

ITP 342 Mobile App Development. Data Persistence

Mobile Application Programming. Data and Persistence

Core Data Potpourri. Paul

Document-Based App Programming Guide for Mac

Cisco StadiumVision Mobile API for Apple ios

Introducing the Photos Frameworks

CS193p Spring 2010 Wednesday, May 26, 2010

DOWNLOAD PDF CORE DATA PROGRAMMING GUIDE

Mobile Application Programming. Data and Persistence

Mobile Application Development L12: Storage & Communication

Stanford CS193p. Developing Applications for ios. Fall Stanford CS193p. Fall 2011

File System Programming Guide

View Controller Lifecycle

Saving Data in ios Hands-On Challenges

Files & Archiving. Lecture 8

lecture 8 & 9 Data Persistence + AVFoundation & Location

ios Core Data Example Application

ITP 342 Advanced Mobile App Dev. Memory

CloudKit Tips And Tricks

Creating Extensions for ios and OS X, Part Two

Developing Applications for ios

Stanford CS193p. Developing Applications for ios. Fall CS193p. Fall

Citizen developer tools are not just for citizen developers!

AVAudioRecorder & System Sound Services

Cisco StadiumVision Mobile API for Apple ios

CS193p Spring 2010 Thursday, April 29, 2010

Review. Objective-C Classes, Methods, Properties, Protocols, Delegation, Memory Management

COCOA WORKSHOP PART 1. Andreas Monitzer

Customizing DAZ Studio

Assignment II: Foundation Calculator

Stanford CS193p. Developing Applications for ios. Winter CS193p! Winter 2015

Signals Documentation

Stanford CS193p. Developing Applications for iphone 4, ipod Touch, & ipad Spring Stanford CS193p Spring 2011

Bindings Example Exercise James Dempsey - WWDC Pre-Show Cocoa Workshop

COSC$4355/6355$ $Introduction$to$Ubiquitous$Computing$ Exercise$3$ September!17,!2015!

Cross Platform Nearby Networking

Advanced Memory Analysis with Instruments. Daniel Delwood Performance Tools Engineer

App Extension Best Practices

Stanford CS193p. Developing Applications for iphone 4, ipod Touch, & ipad Fall Stanford CS193p Fall 2010

Functional Reactive Programming on ios

Section 2: Developer tools and you. Alex Mariakakis (staff-wide)

CS193E Lecture 14. Cocoa Bindings

For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to

Using and Extending the Xcode Source Editor

Game Center Techniques, Part 1

Grand Central Dispatch and NSOperation. CSCI 5828: Foundations of Software Engineering Lecture 28 12/03/2015

Contents. iphone Training. Industry Trainers. Classroom Training Online Training ON-DEMAND Training. Read what you need

Oracle Cloud. Content and Experience Cloud ios Mobile Help E

The Power of Predicates (Yes == NO) == NO

ReactiveCocoa. Marc Prud'hommeaux Ottawa CocoaHeads February 13th, 2014

DL/ID Parsing Component for ios

Stanford CS193p. Developing Applications for ios. Winter CS193p! Winter 2015

Evaluation Guide for ASP.NET Web CMS and Experience Platforms

CS193P - Lecture 3. iphone Application Development. Custom Classes Object Lifecycle Autorelease Properties

Assignment II: Calculator Brain

Assignment III: Graphing Calculator

What s New in Core Data?

Debugging and Profiling

Mobile Application Development L14: Miscellaneous

Oracle Cloud. Content and Experience Cloud Android Mobile Help E

CompsFromSpreadsheet Version 5.1 user guide

Getting Help. iphone Application Programming Lecture 3: Foundation Classes. Data Structures in Objective C. Online Documentation.

Code Examples. C# demo projects. PHP Rest Client

Copy Data From One Schema To Another In Sql Developer

Assignment IV: Smashtag Mentions

Objective-C. Deck.m. Deck.h. Let s look at another class. This one represents a deck of cards. #import <Foundation/Foundation.h> #import "Deck.

WorldCat knowledge base Release Notes for Contents

Cross-Platform Parallels: Understanding SharePoint (Online) Through Notes-colored glasses

Stanford CS193p. Developing Applications for ios. Winter CS193p! Winter 2015

Apple introduced MapKit with ios, maps were based on Google.

NSObject. - (NSString *)description Provides us with a string description of the object

Seamless Linking to Your App

Stanford CS193p. Developing Applications for ios. Spring CS193p. Spring 2016

Data Storage. Dr. Sarah Abraham

Scaling Without Sharding. Baron Schwartz Percona Inc Surge 2010

Transcription:

Developing Applications for ios

Today icloud Sharing documents among a user s devices

Fundamentally: nothing more than a URL of a shared directory However, since it is over the network, there are lots of things to consider. Most importantly, latency and the ramifications of shared access. Entitlements In order for your application to access the cloud, you must set up its entitlements. Luckily this is a single button click in Xcode:

The URL Assuming you just have one container in your Entitlements... [[NSFileManager defaultmanager] URLForUbiquityContainerIdentifier:nil]; Usually you put your documents in the @ Documents directory (special) inside this URL. NSFileManager You can use it, but you don t want to use it in the main thread (it s happening over the network). Don t use it to enumerate the contents of directories (need an always-updating query for that). And you also will want to coordinate any file operations with other devices. Coordination happens among NSFilePresenters using the NSFileCoordinator class. NSFilePresenter This class is an abstraction for something that presents the data of a file/directory to the user. Your presenter would get involved whenever a coordinated change to the file/directory occurs. Not going to cover NSFilePresenter s API in this class. Instead, we ll talk about UIManagedDocument (which is an NSFilePresenter).

UIDocument An NSFilePresenter. Abstraction for a document. Automatically coordinates changes to the document. Primary methods you d override would be... - (id)contentsfortype:(nsstring *)type error:(nserror **)error; - (BOOL)loadFromContents:(id)contents oftype:(nsstring *)type error:(nserror **)error; If your data is stored in a Core Data database, though, you d use UIManagedDocument. UIManagedDocument Fully icloud capable. You need only sign up for the appropriate notifications to keep your UI in sync. Put your UIManagedDocuments into the Documents directory in icloud. iclouddocumentsurl = [icloudurl URLByAppendingPathComponent:@ Documents ];

Only UIManagedDocument changes should be synced to icloud Uploading only a log of changes is a lot better performing than uploading the whole database! To get this, you must set your document s persistentstoreoptions dictionary to include these... NSPersistentStoreUbiquitousContentNameKey (the name of the document) NSPersistentStoreUbiquitousContentURLKey (where all change logs are stored in icloud) Change logs directory (ContentURLKey) should not be stored in the Documents directory in icloud! ContentURLKey is something like [icloudurl URLByAppendingPathComponent:@ CoreData ] All of your documents can share the same ContentURLKey. Document Metadata Strictly speaking, you should get the ContentNameKey from the document s metadata. You can read it from DocumentMetadata.plist inside the document s file wrapper. For example, if docurl were the URL that pointed to the UIManagedDocument in the cloud, then create a dictionary from the following URL (coordinated!) to get the values for the keys... NSURL *metadataurl = [docurl URLByAppendingPathComponent:@ DocumentMetadata.plist ]; Then set the keys in persistentstoreoptions, and then call openwithcompletionhandler:.

Enumerating what s in the Cloud Create a query, start it, then watch for NSNotifications that the results have changed. Creating a query NSMetadataQuery *query = [[NSMetadataQuery alloc] init]; query.searchscopes = [NSArray arraywithobjects:scope1, scope2, nil]; NSMetadataQueryUbiquitousDocumentsScope is all files in the Documents directory. NSMetadataQueryUbiquitousDataScope is all files NOT in the Documents directory. query.predicate = [NSPredicate predicatewithformat:@ %K like *, NSMetadataItemFSNameKey]; // all Starting/stopping the query [query startquery] or [query stopquery] Enabling/disabling NSNotifications [query enableupdates] or [query disableupdates] Probably a good idea to do this in viewwillappear:/viewwilldisappear:

Signing up to receive the query NSNotifications NSNotificationCenter *center = [NSNotificationCenter defaultcenter]; [center addobserver:self selector:@selector(processqueryresults:) name:nsmetadataquerydidfinishgatheringnotification // first results object:query]; [center addobserver:self selector:@selector(processqueryresults:) name:nsmetadataquerydidupdatenotification // subsequent updates object:query]; Don t forget to remove yourself as an observer - (void)dealloc { } [[NSNotificationCenter defaultcenter] removeobserver:self];

Processing NSMetadataQuery NSNotifications - (void)processqueryresults:(nsnotification *)notification } [query disableupdates]; int resultcount = [query resultcount]; for (int i = 0; i < resultcount; i++) { } NSMetadataItem *item = [query resultatindex:i]; NSURL *url = [item valueforattribute:nsmetadataitemurlkey]; // do something with the urls here // but remember that these are URLs of the files inside the file wrapper! [query enableupdates];

Coordinating changes Should be done whenever you access an icloud URL using NSFileManager. Do this outside the main thread! NSFileCoordinator NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initwithfilepresenter:nil]; NSError *coordinationerror; [coordinator coordinatereadingitematurl:(nsurl *)url }]; options:(nsfilecoordinatorreadingoptions)options error:(nserror **)error byaccessor:^(nsurl *urltouse) { // do yo ur NSFileManager stuff here using urltouse if (coordinationerror) { } // handle error Similar methods for coordinating writing, or reading and writing together, or multiple URLs.

Document State It is more important to pay attention to documentstate in an icloud environment. There are two states that occur more often now: EditingDisabled and InConflict. It is also important to watch for SavingError state (and perhaps retry your saves). Conflict What if a device detached from the network changed a document that another device changed? And then the detached device reattached and tried to apply the change and it conflicted? You must manage this conflict by looking for the InConflict document state. When it happens, you must decide which version of the document to use and/or merge changes. Probably want to set your NSManagedObjectContext s mergepolicy to other than default (Error). Then update the old, conflicting NSFileVersions to no longer conflict (and remove those versions). See the demo for a simple example of how to just take the most recent version. Editing Disabled Don t let the user modify a document that is in the EditingDisabled state.

Moving a file to or from icloud It would be nice to allow your users to choose whether a document is shared via icloud or not. You can switch a document from being shared or not at any time that you are connect to icloud. Always do this outside the main thread. API Example of exporting to icloud (you can also go the opposite direction)... dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_default, 0), ^{ NSURL *localurl =...; // url of document to transfer to icloud }); NSString *name = [localurl lastpathcomponent]; NSURL *icloudurl = [iclouddocumentsurl URLByAppendingPathComponent:name]; NSError *error = nil; [[[NSFileManager alloc] init] setubiquitous:yes itematurl:localurl destinationurl:icloudurl error:&error]; // move the document

Sharing a file via icloud icloud is mostly for a single user to share stuff between his or her own devices. However, it is also possible to temporarily export a URL to share a file between users. Only files (not directories) maybe exported in this way. The URL points to a copy of the file (so it is a read-only sharing mechanism). API NSURL *urltoshare =...; NSDate *date; NSError *error; NSURL *sharedurl = [[NSFileManager defaultmanager] URLForPublishingUbiquitousItemAtURL:urlToShare expirationdate:&date error:&error];

NSUbiquitousKeyValueStore Like NSUserDefaults, but icloud-style. Very limited in size (64kb) (overall and per value). Use [NSUbiquitousKeyValueStore defaultstore] to get the shared instance. Set and get just like NSUserDefaults NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultstore]; [store setobject:@ MyValue forkey:@ MyKey ]; [store synchronize]; // not instantaneous! this is networking! Synchronize synchronizes both ways, so a good idea to call it in your app s launch somewhere.

Since store can change at any time, need NSNotification NSNotificationCenter *center = [NSNotificationCenter defaultcenter]; [center addobserver:self selector:@selector(ubiquitouskeyvaluestorechanged:) name:nsubiquitouskeyvaluestoredidchangeexternallynotification object:[nsubiquitouskeyvaluestore defaultstore]]; - (void)ubiquitouskeyvaluestorechanged:(nsnotification *)notification { notification.userinfo contains... NSUbiquitousKeyValueStoreChangeReasonKey (Server, InitialSync, QuotaViolation) NSUbiquitousKeyValueStoreChangedKeysKey (NSArray of NSStrings of keys that changed) } Does NOT get called if YOU change a key, only if the cloud does!

Demo icloud (two-day demo) Finding out what documents are stored in the cloud Storing/Retrieving Core Data documents (UIManagedDocuments) Deleting documents from the cloud (NSFileCoordinator) Noticing changes to documents in real time Handling file version conflicts by watching for documentstate changes Cloud NSUserDefaults equivalent Along the way... Getting a random queue to do work on (rather than creating a named one) Generic icloud-document-handling view controller NSNotifications Flexible table view prepareforsegue:sender: implementation Migrating (automatically) your Core Data schema to a new version Using AskerViewController again Editing table views (by allowing rows to be deleted)

Coming Up Thursday More demo! Friday Section OpenGL