09 Data

2,166
-1

Published on

Published in: Technology, News & Politics
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,166
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
62
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

09 Data

  1. 1. CS193P - Lecture 9 iPhone Application Development Data in Your iPhone App Chris Marcellino Tuesday, February 2, 2010 1
  2. 2. Today’s Topics • Data in Your iPhone App ■ Saving & loading local data ■ Accessing remote data over the Internet Tuesday, February 2, 2010 2
  3. 3. Today’s Topics • Property Lists, NSUserDefaults and Settings • iPhone’s File System • Archiving Objects • The Joy of SQLite • JSON • Apple Push Notification Service Tuesday, February 2, 2010 3
  4. 4. Property Lists Tuesday, February 2, 2010 4
  5. 5. Property Lists • Convenient way to store a small amount of data ■ Arrays, dictionaries, strings, numbers, dates, raw data ■ Human-readable XML or binary format • NSUserDefaults class uses property lists under the hood Tuesday, February 2, 2010 5
  6. 6. When Not to Use Property Lists • More than a few hundred KB of data ■ Loading a property list is all-or-nothing • Complex object graphs • Custom object types • Multiple writers (e.g. not ACID) Tuesday, February 2, 2010 6
  7. 7. Reading & Writing Property Lists • NSArray and NSDictionary convenience methods • Operate recursively // Writing - (BOOL)writeToFile:(NSString *)aPath atomically:(BOOL)flag; - (BOOL)writeToURL:(NSURL *)aURL atomically:(BOOL)flag; // Reading - (id)initWithContentsOfFile:(NSString *)aPath; - (id)initWithContentsOfURL:(NSURL *)aURL; Tuesday, February 2, 2010 7
  8. 8. Writing an Array to Disk Tuesday, February 2, 2010 8
  9. 9. Writing an Array to Disk NSArray *array = [NSArray arrayWithObjects:@“Foo”, Tuesday, February 2, 2010 8
  10. 10. Writing an Array to Disk NSArray *array = [NSArray arrayWithObjects:@“Foo”, [NSNumber numberWithBool:YES], Tuesday, February 2, 2010 8
  11. 11. Writing an Array to Disk NSArray *array = [NSArray arrayWithObjects:@“Foo”, [NSNumber numberWithBool:YES], [NSDate dateWithTimeIntervalSinceNow:60], Tuesday, February 2, 2010 8
  12. 12. Writing an Array to Disk NSArray *array = [NSArray arrayWithObjects:@“Foo”, [NSNumber numberWithBool:YES], [NSDate dateWithTimeIntervalSinceNow:60], nil]; Tuesday, February 2, 2010 8
  13. 13. Writing an Array to Disk NSArray *array = [NSArray arrayWithObjects:@“Foo”, [NSNumber numberWithBool:YES], [NSDate dateWithTimeIntervalSinceNow:60], nil]; [array writeToFile:@“MyArray.plist” atomically:YES]; Tuesday, February 2, 2010 8
  14. 14. Writing an Array to Disk NSArray *array = [NSArray arrayWithObjects:@“Foo”, [NSNumber numberWithBool:YES], [NSDate dateWithTimeIntervalSinceNow:60], nil]; [array writeToFile:@“MyArray.plist” atomically:YES]; <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <array> <string>Foo</string> <true/> <date>2010-02-02T09:26:18Z</date> </array> </plist> Tuesday, February 2, 2010 8
  15. 15. Writing a Dictionary to Disk Tuesday, February 2, 2010 9
  16. 16. Writing a Dictionary to Disk NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: Tuesday, February 2, 2010 9
  17. 17. Writing a Dictionary to Disk NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: @“Bob”, @“Name”, Tuesday, February 2, 2010 9
  18. 18. Writing a Dictionary to Disk NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: @“Bob”, @“Name”, [NSNumber numberWithInt:9], @“Lecture”, Tuesday, February 2, 2010 9
  19. 19. Writing a Dictionary to Disk NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: @“Bob”, @“Name”, [NSNumber numberWithInt:9], @“Lecture”, nil]; Tuesday, February 2, 2010 9
  20. 20. Writing a Dictionary to Disk NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: @“Bob”, @“Name”, [NSNumber numberWithInt:9], @“Lecture”, nil]; [dict writeToFile:@“MyDict.plist” atomically:YES]; Tuesday, February 2, 2010 9
  21. 21. Writing a Dictionary to Disk NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: @“Bob”, @“Name”, [NSNumber numberWithInt:9], @“Lecture”, nil]; [dict writeToFile:@“MyDict.plist” atomically:YES]; <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Name</key> <string>Bob</string> <key>Lecture</key> <integer>10</integer> </dict> </plist> Tuesday, February 2, 2010 9
  22. 22. NSPropertyListSerialization • Allows finer-grained control ■ File format ■ More descriptive errors ■ Mutability Tuesday, February 2, 2010 10
  23. 23. NSPropertyListSerialization • Allows finer-grained control ■ File format ■ More descriptive errors ■ Mutability // Property list to NSData + (NSData *)dataFromPropertyList:(id)plist format:(NSPropertyListFormat)format errorDescription:(NSString **)errorString; // NSData to property list + (id)propertyListFromData:(NSData *)data mutabilityOption:(NSPropertyListMutabilityOptions)opt format:(NSPropertyListFormat *)format errorDescription:(NSString **)errorString; Tuesday, February 2, 2010 10
  24. 24. More on Property Lists • “Property List Programming Guide for Cocoa” http://developer.apple.com/documentation/Cocoa/ Conceptual/PropertyLists/ Tuesday, February 2, 2010 11
  25. 25. iPhone’s File System Tuesday, February 2, 2010 12
  26. 26. Keeping Applications Separate Image (cc) by davidsilver on Flickr Tuesday, February 2, 2010 13
  27. 27. Why Keep Applications Separate? • Security • Privacy • Cleanup after deleting an app Tuesday, February 2, 2010 14
  28. 28. Home Directory Layout Tuesday, February 2, 2010 15
  29. 29. Home Directory Layout • Each app has its own set of directories Tuesday, February 2, 2010 15
  30. 30. Home Directory Layout • Each app has its own set of directories • <Application Home> Tuesday, February 2, 2010 15
  31. 31. Home Directory Layout • Each app has its own set of directories • <Application Home> ■ MyApp.app Tuesday, February 2, 2010 15
  32. 32. Home Directory Layout • Each app has its own set of directories • <Application Home> ■ MyApp.app ■ MyApp Tuesday, February 2, 2010 15
  33. 33. Home Directory Layout • Each app has its own set of directories • <Application Home> ■ MyApp.app ■ MyApp ■ MainWindow.nib Tuesday, February 2, 2010 15
  34. 34. Home Directory Layout • Each app has its own set of directories • <Application Home> ■ MyApp.app ■ MyApp ■ MainWindow.nib ■ SomeImage.png Tuesday, February 2, 2010 15
  35. 35. Home Directory Layout • Each app has its own set of directories • <Application Home> ■ MyApp.app ■ MyApp ■ MainWindow.nib ■ SomeImage.png ■ Documents Tuesday, February 2, 2010 15
  36. 36. Home Directory Layout • Each app has its own set of directories • <Application Home> ■ MyApp.app ■ MyApp ■ MainWindow.nib ■ SomeImage.png ■ Documents ■ Library Tuesday, February 2, 2010 15
  37. 37. Home Directory Layout • Each app has its own set of directories • <Application Home> ■ MyApp.app ■ MyApp ■ MainWindow.nib ■ SomeImage.png ■ Documents ■ Library ■ Caches Tuesday, February 2, 2010 15
  38. 38. Home Directory Layout • Each app has its own set of directories • <Application Home> ■ MyApp.app ■ MyApp ■ MainWindow.nib ■ SomeImage.png ■ Documents ■ Library ■ Caches ■ Preferences Tuesday, February 2, 2010 15
  39. 39. Home Directory Layout • Each app has its own set of directories • <Application Home> ■ MyApp.app ■ MyApp ■ MainWindow.nib ■ SomeImage.png ■ Documents ■ Library ■ Caches ■ Preferences • Applications only read and write within their home directory Tuesday, February 2, 2010 15
  40. 40. Home Directory Layout • Each app has its own set of directories • <Application Home> ■ MyApp.app ■ MyApp ■ MainWindow.nib ■ SomeImage.png ■ Documents ■ Library ■ Caches ■ Preferences • Applications only read and write within their home directory • Backed up by iTunes during sync (mostly) Tuesday, February 2, 2010 15
  41. 41. File Paths in Your Application Tuesday, February 2, 2010 16
  42. 42. File Paths in Your Application // Basic directories NSString *homePath = NSHomeDirectory(); NSString *tmpPath = NSTemporaryDirectory(); Tuesday, February 2, 2010 16
  43. 43. File Paths in Your Application // Basic directories NSString *homePath = NSHomeDirectory(); NSString *tmpPath = NSTemporaryDirectory(); // Documents directory NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsPath = [paths objectAtIndex:0]; Tuesday, February 2, 2010 16
  44. 44. File Paths in Your Application // Basic directories NSString *homePath = NSHomeDirectory(); NSString *tmpPath = NSTemporaryDirectory(); // Documents directory NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsPath = [paths objectAtIndex:0]; // <Application Home>/Documents/foo.plist NSString *fooPath = [documentsPath stringByAppendingPathComponent:@“foo.plist”]; Tuesday, February 2, 2010 16
  45. 45. Including Writable Files with Your App • Many applications want to include some starter data • But application bundles are code signed ■ You can’t modify the contents of your app bundle • To include a writable data file with your app... ■ Build it as part of your app bundle ■ On first launch, copy it to your Documents directory Tuesday, February 2, 2010 17
  46. 46. Archiving Objects Tuesday, February 2, 2010 18
  47. 47. Archiving Objects • Next logical step from property lists ■ Include arbitrary classes ■ Complex object graphs • Used by Interface Builder for NIBs Tuesday, February 2, 2010 19
  48. 48. Making Objects Archivable • Conform to the <NSCoding> protocol Tuesday, February 2, 2010 20
  49. 49. Making Objects Archivable • Conform to the <NSCoding> protocol // Encode an object for an archive - (void)encodeWithCoder:(NSCoder *)coder { [super encodeWithCoder:coder]; [coder encodeObject:name forKey:@“Name”]; [coder encodeInteger:numberOfSides forKey:@“Sides”]; } // Decode an object from an archive - (id)initWithCoder:(NSCoder *)coder { self = [super initWithCoder:coder]; name = [[coder decodeObjectForKey:@“Name”] retain]; numberOfSides = [coder decodeIntegerForKey:@“Side”]; } Tuesday, February 2, 2010 20
  50. 50. Archiving & Unarchiving Object Graphs Tuesday, February 2, 2010 21
  51. 51. Archiving & Unarchiving Object Graphs • Creating an archive NSArray *polygons = ...; NSString *path = ...; BOOL result = [NSKeyedArchiver archiveRootObject:polygons toFile:path]; Tuesday, February 2, 2010 21
  52. 52. Archiving & Unarchiving Object Graphs • Creating an archive NSArray *polygons = ...; NSString *path = ...; BOOL result = [NSKeyedArchiver archiveRootObject:polygons toFile:path]; • Decoding an archive NSArray *polygons = nil; NSString *path = ...; polygons = [NSKeyedUnarchiver unarchiveObjectWithFile:path]; Tuesday, February 2, 2010 21
  53. 53. More on Archiving Objects • “Archives and Serializations Programming Guide for Cocoa” http://developer.apple.com/documentation/Cocoa/ Conceptual/Archiving/ Tuesday, February 2, 2010 22
  54. 54. The Joy of SQLite Tuesday, February 2, 2010 23
  55. 55. SQLite • Complete SQL database in an ordinary file • Simple, compact, fast, reliable • No server • Free/Open Source Software • Great for embedded devices ■ Included on the iPhone platform Tuesday, February 2, 2010 24
  56. 56. When Not to Use SQLite • Multi-gigabyte databases • High concurrency (multiple writers) • Client-server applications • “Appropriate Uses for SQLite” http://www.sqlite.org/whentouse.html Tuesday, February 2, 2010 25
  57. 57. SQLite C API Basics Tuesday, February 2, 2010 26
  58. 58. SQLite C API Basics • Open the database int sqlite3_open(const char *filename, sqlite3 **db); Tuesday, February 2, 2010 26
  59. 59. SQLite C API Basics • Open the database int sqlite3_open(const char *filename, sqlite3 **db); • Execute a SQL statement int sqlite3_exec(sqlite3 *db, const char *sql, int (*callback)(void*,int,char**,char**), void *context, char **error); Tuesday, February 2, 2010 26
  60. 60. SQLite C API Basics • Open the database int sqlite3_open(const char *filename, sqlite3 **db); • Execute a SQL statement int sqlite3_exec(sqlite3 *db, const char *sql, int (*callback)(void*,int,char**,char**), void *context, char **error); // Your callback int callback(void *context, int count, char **values, char **columns); Tuesday, February 2, 2010 26
  61. 61. SQLite C API Basics • Open the database int sqlite3_open(const char *filename, sqlite3 **db); • Execute a SQL statement int sqlite3_exec(sqlite3 *db, const char *sql, int (*callback)(void*,int,char**,char**), void *context, char **error); // Your callback int callback(void *context, int count, char **values, char **columns); • Close the database int sqlite3_close(sqlite3 *db); Tuesday, February 2, 2010 26
  62. 62. Demo: Simple SQLite Tuesday, February 2, 2010 27
  63. 63. More on SQLite • “SQLite in 5 Minutes Or Less” http://www.sqlite.org/quickstart.html • “Intro to the SQLite C Interface” http://www.sqlite.org/cintro.html Tuesday, February 2, 2010 28
  64. 64. Core Data • Object-graph management and persistence framework ■ Makes it easy to save & load model objects ■ Properties ■ Relationships ■ Higher-level abstraction than SQLite or property lists • Available on the Mac OS X desktop • Now available on iPhone OS 3.0 Tuesday, February 2, 2010 29
  65. 65. Two classes you should know about... Tuesday, February 2, 2010 30
  66. 66. Two classes you should know about... • NSPredicate Tuesday, February 2, 2010 30
  67. 67. Two classes you should know about... • NSPredicate ■ “Used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.” Tuesday, February 2, 2010 30
  68. 68. Two classes you should know about... • NSPredicate ■ “Used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.” ■ -[NSPredicate predicateWithFormat:] Tuesday, February 2, 2010 30
  69. 69. Two classes you should know about... • NSPredicate ■ “Used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.” ■ -[NSPredicate predicateWithFormat:] ■ Simple comparisons: Tuesday, February 2, 2010 30
  70. 70. Two classes you should know about... • NSPredicate ■ “Used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.” ■ -[NSPredicate predicateWithFormat:] ■ Simple comparisons: ■ grade == “7” Tuesday, February 2, 2010 30
  71. 71. Two classes you should know about... • NSPredicate ■ “Used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.” ■ -[NSPredicate predicateWithFormat:] ■ Simple comparisons: ■ grade == “7” ■ user.firstName like "Tom" Tuesday, February 2, 2010 30
  72. 72. Two classes you should know about... • NSPredicate ■ “Used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.” ■ -[NSPredicate predicateWithFormat:] ■ Simple comparisons: ■ grade == “7” ■ user.firstName like "Tom" ■ “first contains [c]”chris” Tuesday, February 2, 2010 30
  73. 73. Two classes you should know about... • NSPredicate ■ “Used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.” ■ -[NSPredicate predicateWithFormat:] ■ Simple comparisons: ■ grade == “7” ■ user.firstName like "Tom" ■ “first contains [c]”chris” ■ Many, many options: http://developer.apple.com/mac/library/documentation/cocoa/ Conceptual/Predicates/Articles/pSyntax.html Tuesday, February 2, 2010 30
  74. 74. Two classes you should know about... Tuesday, February 2, 2010 31
  75. 75. Two classes you should know about... • NSEntityDescription Tuesday, February 2, 2010 31
  76. 76. Two classes you should know about... • NSEntityDescription ■ Used for inserting a new object into a Core Data Managed Object context Tuesday, February 2, 2010 31
  77. 77. Two classes you should know about... • NSEntityDescription ■ Used for inserting a new object into a Core Data Managed Object context ■ - [NSEntityDescription insertNewObjectForEntityForName:inManagedObjectContext:] Tuesday, February 2, 2010 31
  78. 78. Two classes you should know about... • NSEntityDescription ■ Used for inserting a new object into a Core Data Managed Object context ■ - [NSEntityDescription insertNewObjectForEntityForName:inManagedObjectContext:] ■ See the documentation! Tuesday, February 2, 2010 31
  79. 79. Two classes you should know about... • NSEntityDescription ■ Used for inserting a new object into a Core Data Managed Object context ■ - [NSEntityDescription insertNewObjectForEntityForName:inManagedObjectContext:] ■ See the documentation! ■ http://developer.apple.com/mac/library/documentation/cocoa/ reference/CoreDataFramework/Classes/ NSEntityDescription_Class/NSEntityDescription.html Tuesday, February 2, 2010 31
  80. 80. Web Services Tuesday, February 2, 2010 32
  81. 81. Your Application & The Cloud • Store & access remote data • May be under your control or someone else’s • Many Web 2.0 apps/sites provide developer API Tuesday, February 2, 2010 33
  82. 82. “I made a location-based user-generated video blogging mashup... for pets!” Tuesday, February 2, 2010 34
  83. 83. Integrating with Web Services • Non-goal of this class: teach you all about web services ■ Plenty of tutorials accessible, search on Google • Many are exposed via RESTful interfaces with XML or JSON ■ REpresentational State Transfer ■ Stateless interactions ■ Well defined client/server roles & interfaces ■ e.g. HTTP • High level overview of parsing these types of data Tuesday, February 2, 2010 35
  84. 84. XML Tuesday, February 2, 2010 36
  85. 85. Options for Parsing XML • libxml2 ■ Tree-based: easy to parse, entire tree in memory ■ Event-driven: less memory, more complex to manage state ■ Text reader: fast, easy to write, efficient • NSXMLParser ■ Event-driven API: simpler but less powerful than libxml2 Tuesday, February 2, 2010 37
  86. 86. More on Parsing XML • Brent Simmons, “libxml2 + xmlTextReader on Macs” http://inessential.com/?comments=1&postid=3489 ■ Includes example of parsing Twitter XML! • Big Nerd Ranch, “Parsing XML in Cocoa” http://weblog.bignerdranch.com/?p=48 ■ Covers the basics of NSXMLReader Tuesday, February 2, 2010 38
  87. 87. JSON Tuesday, February 2, 2010 39
  88. 88. JavaScript Object Notation • More lightweight than XML • Looks a lot like a property list ■ Arrays, dictionaries, strings, numbers • Open source json-framework wrapper for Objective-C Tuesday, February 2, 2010 40
  89. 89. What does a JSON object look like? Tuesday, February 2, 2010 41
  90. 90. What does a JSON object look like? { Tuesday, February 2, 2010 41
  91. 91. What does a JSON object look like? { “instructor” : “Josh Shaffer”, Tuesday, February 2, 2010 41
  92. 92. What does a JSON object look like? { “instructor” : “Josh Shaffer”, “students” : 60, Tuesday, February 2, 2010 41
  93. 93. What does a JSON object look like? { “instructor” : “Josh Shaffer”, “students” : 60, “itunes-u” : true, Tuesday, February 2, 2010 41
  94. 94. What does a JSON object look like? { “instructor” : “Josh Shaffer”, “students” : 60, “itunes-u” : true, “midterm-exam” : null, Tuesday, February 2, 2010 41
  95. 95. What does a JSON object look like? { “instructor” : “Josh Shaffer”, “students” : 60, “itunes-u” : true, “midterm-exam” : null, “assignments” : [ “WhatATool”, Tuesday, February 2, 2010 41
  96. 96. What does a JSON object look like? { “instructor” : “Josh Shaffer”, “students” : 60, “itunes-u” : true, “midterm-exam” : null, “assignments” : [ “WhatATool”, “HelloPoly”, Tuesday, February 2, 2010 41
  97. 97. What does a JSON object look like? { “instructor” : “Josh Shaffer”, “students” : 60, “itunes-u” : true, “midterm-exam” : null, “assignments” : [ “WhatATool”, “HelloPoly”, “Presence” ] Tuesday, February 2, 2010 41
  98. 98. What does a JSON object look like? { “instructor” : “Josh Shaffer”, “students” : 60, “itunes-u” : true, “midterm-exam” : null, “assignments” : [ “WhatATool”, “HelloPoly”, “Presence” ] } Tuesday, February 2, 2010 41
  99. 99. Using json-framework • Reading a JSON string into Foundation objects Tuesday, February 2, 2010 42
  100. 100. Using json-framework • Reading a JSON string into Foundation objects #import <JSON/JSON.h> Tuesday, February 2, 2010 42
  101. 101. Using json-framework • Reading a JSON string into Foundation objects #import <JSON/JSON.h> // Get a JSON string from the cloud NSString *jsonString = ...; Tuesday, February 2, 2010 42
  102. 102. Using json-framework • Reading a JSON string into Foundation objects #import <JSON/JSON.h> // Get a JSON string from the cloud NSString *jsonString = ...; // Parsing will result in Foundation objects // Top level may be an NSDictionary or an NSArray id object = [jsonString JSONValue]; Tuesday, February 2, 2010 42
  103. 103. Using json-framework • Writing a JSON string from Foundation objects Tuesday, February 2, 2010 43
  104. 104. Using json-framework • Writing a JSON string from Foundation objects // Create some data in your app Tuesday, February 2, 2010 43
  105. 105. Using json-framework • Writing a JSON string from Foundation objects // Create some data in your app NSDictionary *dictionary = ...; // Convert into a JSON string before sending to the cloud Tuesday, February 2, 2010 43
  106. 106. Using json-framework • Writing a JSON string from Foundation objects // Create some data in your app NSDictionary *dictionary = ...; // Convert into a JSON string before sending to the cloud jsonString = [dictionary JSONRepresentation]; Tuesday, February 2, 2010 43
  107. 107. Demo: Flickr API with JSON Tuesday, February 2, 2010 44
  108. 108. More on JSON • “JSON Parser/Generator for Objective-C” http://code.google.com/p/json-framework/ • “Introducing JSON” http://www.json.org/ Tuesday, February 2, 2010 45
  109. 109. Apple Push Notification Service Tuesday, February 2, 2010 46
  110. 110. Overview Tuesday, February 2, 2010 47
  111. 111. Overview • Show badges, alerts and play sounds without app running Tuesday, February 2, 2010 47
  112. 112. Overview • Show badges, alerts and play sounds without app running • Minimal server infrastructure needed Tuesday, February 2, 2010 47
  113. 113. Overview • Show badges, alerts and play sounds without app running • Minimal server infrastructure needed • Preserves battery life: 1 versus n TCP/IP connections Apple Server Push Service Tuesday, February 2, 2010 47
  114. 114. Using the Service Server Tuesday, February 2, 2010 48
  115. 115. Using the Service What you need Server Tuesday, February 2, 2010 48
  116. 116. Using the Service What you need Server Tuesday, February 2, 2010 48
  117. 117. Using the Service What you need Server edu.stanford.cs193.app Tuesday, February 2, 2010 48
  118. 118. Using the Service What you need Server edu.stanford.cs193.app Tuesday, February 2, 2010 48
  119. 119. Using the Service What you do Apple Push Server Service Tuesday, February 2, 2010 49
  120. 120. Using the Service 1. Register with the service Apple Push Chris’s iPhone Service Tuesday, February 2, 2010 50
  121. 121. Using the Service Chris’s iPhone Server Tuesday, February 2, 2010 51
  122. 122. Using the Service 2. Send token to your server Server Chris’s iPhone Tuesday, February 2, 2010 51
  123. 123. Using the Service 3. Send notifications Apple Push Server Service Chris’s iPhone Tuesday, February 2, 2010 52
  124. 124. Using the Service 3. Send notifications Apple Push JSON Service Server Chris’s iPhone Tuesday, February 2, 2010 52
  125. 125. Using the Service 4. Receive notifications Apple Push Service Tuesday, February 2, 2010 53
  126. 126. Using the Service 4. Receive notifications Apple Push JSON Service Tuesday, February 2, 2010 53
  127. 127. Using the Service 1. Register with the service Apple Push Chris’s iPhone Service Tuesday, February 2, 2010 54
  128. 128. Using the Service 1. Register with the service Apple Push Chris’s iPhone Service Tuesday, February 2, 2010 54
  129. 129. Registering with the Service Application launch • UIKit API in UIApplication.h to register ■ Pass the types you want to receive -(void)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options { // Register this app on this device UIRemoteNotificationType myTypes = UIRemoteNotificationTypeSounds | UIRemoteNotificationTypeBadges; [application registerForRemoteNotificationTypes:myTypes]; } Tuesday, February 2, 2010 55
  130. 130. Registering with the Service Delegate callbacks Tuesday, February 2, 2010 56
  131. 131. Registering with the Service Delegate callbacks - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)token { // Phone home with device token } Tuesday, February 2, 2010 56
  132. 132. Registering with the Service Delegate callbacks - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)token { // Phone home with device token } - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { // Oh noes! Check your Provisioning Profile on device and in Xcode } Tuesday, February 2, 2010 56
  133. 133. Registering with the Service 96385da767191121a851963983fdac9bbdf74dcf6219ae14ed8d08228 Tuesday, February 2, 2010 57
  134. 134. Registering with the Service The device token 96385da767191121a851963983fdac9bbdf74dcf6219ae14ed8d08228 Tuesday, February 2, 2010 57
  135. 135. Registering with the Service The device token • Uniquely identifies device 96385da767191121a851963983fdac9bbdf74dcf6219ae14ed8d08228 Tuesday, February 2, 2010 57
  136. 136. Registering with the Service The device token • Uniquely identifies device ■ Distinct from -[UIDevice deviceIdentifier] 96385da767191121a851963983fdac9bbdf74dcf6219ae14ed8d08228 Tuesday, February 2, 2010 57
  137. 137. Registering with the Service The device token • Uniquely identifies device ■ Distinct from -[UIDevice deviceIdentifier] • Just call registration API again if token is needed 96385da767191121a851963983fdac9bbdf74dcf6219ae14ed8d08228 Tuesday, February 2, 2010 57
  138. 138. Registering for Notifications Optional callbacks and methods • UIApplicationDelegate - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo Tuesday, February 2, 2010 58
  139. 139. Registering for Notifications Optional callbacks and methods • UIApplicationDelegate - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo • UIApplication - (UIRemoteNotificationType)enabledRemoteNotificationTypes Tuesday, February 2, 2010 58
  140. 140. Using the Service Chris’s iPhone Server Tuesday, February 2, 2010 59
  141. 141. Using the Service 2. Send token to your server Server Chris’s iPhone Tuesday, February 2, 2010 59
  142. 142. Using the Service 3. Send notifications Apple Push Server Service Chris’s iPhone Tuesday, February 2, 2010 60
  143. 143. Using the Service 3. Send notifications Apple Push JSON Server Service Chris’s iPhone edu.s.cs193 Tuesday, February 2, 2010 60
  144. 144. Sending Notifications { "aps" : { "alert" : "Jen: Sushi at 10?", "badge" : 1, "sound" : "Jingle.aiff" }, "acme1" : "conversation9964" } Tuesday, February 2, 2010 61
  145. 145. Sending Notifications Message payload { "aps" : { "alert" : "Jen: Sushi at 10?", "badge" : 1, "sound" : "Jingle.aiff" }, "acme1" : "conversation9964" } Tuesday, February 2, 2010 61
  146. 146. Sending Notifications Message payload • Strict RFC 4627 JSON { "aps" : { "alert" : "Jen: Sushi at 10?", "badge" : 1, "sound" : "Jingle.aiff" }, "acme1" : "conversation9964" } Tuesday, February 2, 2010 61
  147. 147. Sending Notifications Message payload • Strict RFC 4627 JSON • 256 byte maximum { "aps" : { "alert" : "Jen: Sushi at 10?", "badge" : 1, "sound" : "Jingle.aiff" }, "acme1" : "conversation9964" } Tuesday, February 2, 2010 61
  148. 148. Sending Notifications Message payload • aps dictionary reserved for the sound, badge or alert keys ■ All keys optional { "aps" : { "alert" : "Jen: Sushi at 10?", "badge" : 1, "sound" : "Jingle.aiff" }, "acme1" : "conversation9964" } • Rest of payload is for your app Tuesday, February 2, 2010 62
  149. 149. Sending Notifications Message payload • aps dictionary reserved for the sound, badge or alert keys ■ All keys optional { "aps" : { "alert" : "Jen: Sushi at 10?", "badge" : 1, "sound" : "Jingle.aiff" }, "acme1" : "conversation9964" } • Rest of payload is for your app Tuesday, February 2, 2010 62
  150. 150. Badges badge key, integer value • Positive integer ■ Or omit to remove { "aps" : { "badge" : 1 } } Tuesday, February 2, 2010 63
  151. 151. Badges badge key, integer value • Positive integer ■ Or omit to remove { "aps" : { "badge" : 1 } } Tuesday, February 2, 2010 63
  152. 152. Sounds sound key, string value • Either a filename in app bundle { ■ linear PCM "aps" : { "sound" : "Jingle.aiff" ■ MA4 } } ■ µLaw ■ aLaw • Or “default” • Vibration is automatic Tuesday, February 2, 2010 64
  153. 153. Alerts alert key, string or dictionary value • Simplest form is just a string value { "aps" : { "alert" : "Jen: Sushi at 10?" } } • Can be localized (see documentation) • Can also customize the text on the view button ■ or omit it Tuesday, February 2, 2010 65
  154. 154. Alerts alert key, string or dictionary value • Simplest form is just a string value { "aps" : { "alert" : "Jen: Sushi at 10?" } } • Can be localized (see documentation) • Can also customize the text on the view button ■ or omit it Tuesday, February 2, 2010 65
  155. 155. Sending the Payload Send JSON that is stripped of whitespace { "aps" : { "alert" : "Jen: Sushi at 10?", "badge" : 1, 150 bytes "sound" : "Jingle1.aiff" }, "acme1" : "conversation9964" Tuesday, February 2, 2010 66
  156. 156. Sending the Payload Send JSON that is stripped of whitespace {"aps":{"alert":"Jen: Sushi at 10?","badge": 1, "sound":"Jingle.aiff"},"acme1":"conversation 9964"} 96 bytes Tuesday, February 2, 2010 66
  157. 157. Demo: Pushing to the Flickr app Tuesday, February 2, 2010 67
  158. 158. NSUserDefaults recap (time permitting) Tuesday, February 2, 2010 68
  159. 159. NSUserDefaults • Convenient way to store settings and lightweight state ■ Arrays, dictionaries, strings, numbers, dates, raw data ■ Settings bundles can be created so that user defaults can be set from Settings app ■ Internally stored as property lists Tuesday, February 2, 2010 69
  160. 160. Reading & Writing User Defaults • Key-value store • Base methods accept and return objects for values + (NSUserDefaults *)standardUserDefaults; - (id)objectForKey:(NSString *)defaultName; - (void)setObject:(id)value forKey:(NSString *)defaultName; - (void)removeObjectForKey:(NSString *)defaultName; - (BOOL)synchronize; Tuesday, February 2, 2010 70
  161. 161. Reading & Writing User Defaults • Many convenience methods that ‘box’ and ‘unbox’ the object ■ and perform type checking - (NSString *)stringForKey:(NSString *)defaultName; - (NSArray *)arrayForKey:(NSString *)defaultName; - (NSDictionary *)dictionaryForKey:(NSString *)defaultName; - (NSData *)dataForKey:(NSString *)defaultName; - (NSArray *)stringArrayForKey:(NSString *)defaultName; - (NSInteger)integerForKey:(NSString *)defaultName; - (float)floatForKey:(NSString *)defaultName; - (double)doubleForKey:(NSString *)defaultName; - (BOOL)boolForKey:(NSString *)defaultName; - (void)setInteger:(NSInteger)value forKey:(NSString *) defaultName; - (void)setFloat:(float)value forKey:(NSString *)defaultName; - (void)setDouble:(double)value forKey:(NSString *)defaultName; - (void)setBool:(BOOL)value forKey:(NSString *)defaultName; Tuesday, February 2, 2010 71
  162. 162. -[NSUserDefaults synchronize] • Call [[NSUserDefaults standardUserDefaults] synchronize] to write changes to disk • Also loads external changes from disk (useful on Mac OS X) Tuesday, February 2, 2010 72
  163. 163. More on NSUserDefaults • “User Defaults Programming Topics for Cocoa” http://developer.apple.com/mac/library/documentation/ Cocoa/Conceptual/UserDefaults/Tasks/UsingDefaults.html Tuesday, February 2, 2010 73
  164. 164. Demo: NSUserDefaults and Settings Tuesday, February 2, 2010 74
  165. 165. Recap • Property lists, NSUserDefaults ■ Quick & easy, but limited • Archived objects ■ More flexible, but require writing a lot of code • SQLite ■ Elegant solution for many types of problems • XML and JSON ■ Low-overhead options for talking to “the cloud” ■ Apple Push Notification Service pushes JSON from your server to devices Tuesday, February 2, 2010 75
  166. 166. Questions? Tuesday, February 2, 2010 76
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×