iPhone Advanced Projects ■■■ Dave Mark, Series Editor Joachim Bondo Ray Kiddy Dylan Bruzenak Noel Llopis Steve Finkelstein Joe Pezzillo Owen Goss Florian Pflug Tom Harrington Jonathan Saggau Peter Honeder Ben Britten Smith iPhone Advanced Projects Copyright © 2009 by Dave Mark, Joachim Bondo, Dylan Bruzenak, Steve Finkelstein, Owen Goss, Tom Harrington, Peter Honeder, Ray Kiddy, Noel Llopis, Joe Pezzillo, Florian Pflug, Jonathan Saggau, Ben Britten Smith All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN-13 (pbk): 978-1-4302-2403-7 ISBN-13 (electronic): 978-1-4302-2404-4 Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1 Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. Lead Editor: Clay Andres Technical Reviewer: Glenn Cole Developmental Editor: Douglas Pundick Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Tony Campbell, Gary Cornell, Jonathan Gennick, Michelle Lowman, Matthew Moodie, Jeffrey Pepper, Frank Pohlmann, Ben Renow- Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh Coordinating Editor: Kelly Moritz Copy Editor: Kim Wimpsett Compositor: MacPS, LLC Indexer: Julie Grady Artist: April Milne Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail [email protected], or visit http://www.springeronline.com. For information on translations, please e-mail [email protected], or visit http://www.apress.com. Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales– eBook Licensing web page at http://www.apress.com/info/bulksales. The information in this book is distributed on an “as is” basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work. The source code for this book is available to readers at http://www.apress.com. You will need to answer questions pertaining to this book in order to successfully download the code. 2ii To my lovely wife, Leonie. —Ben Britten Smith To my wife, Malena, who once again gave me the support I hadn’t earned. —Joachim Bondo To everyone I know and to everyone I haven’t met yet. —Dylan Bruzenak To all of my family and friends for their support and patience with my demanding schedule. To my loving wife, Michelle, who sustains me and encourages me to take risks. Finally, this one is for my grandmother, Asya; you will live forever in all our hearts. —Steve Finkelstein To the iPhone game developers on Twitter for sharing so much and being such a supportive community. —Noel Llopis (@snappytouch on Twitter) I’m so grateful to so many people I can’t possibly hope to name them all individually, so, en masse, let me thank the blessing that is my family (especially my son), the unstoppable geniuses at Apple, the folks at Apress who patiently awaited my writing, the incredibly supportive Mac and iPhone indie developer community, all my clients and customers, my business partners and colleagues, and, of course, the great ineffable spirit of the universe that makes everything possible. Thank you! —Joe Pezzillo To my family, my friends, the island “La Palma,” and the one who introduced me to it. —Florian Pflug To Dr. Michele, who doesn’t let me call her doctor. Thanks for making me type. —Jonathan Saggau iii Contents at a Glance ■Contents at a Glance ................................................................................................................................................................ iv ■Contents .................................................................................................................................................................................... v ■Foreword ................................................................................................................................................................................. xi ■About the Technical Reviewer ................................................................................................................................................ xii ■Preface ................................................................................................................................................................................... xiii Ben Britten Smith ........................................................................................................................................................................ 1 ■Everything You Ever Wanted to Know About Particle Systems ................................................................................................ 3 Joachim Bondo .......................................................................................................................................................................... 37 ■Chess on the ’Net: Correspondence Gaming with Deep Green ................................................................................................ 39 Tom Harrington .......................................................................................................................................................................... 63 ■Audio Streaming: An Exploration into Core Audio .................................................................................................................. 65 Owen Goss ................................................................................................................................................................................. 99 ■You Go Squish Now! Debugging on the iPhone ..................................................................................................................... 101 Dylan Bruzenak ........................................................................................................................................................................ 139 ■Building Data-Driven Applications with Active Record and SQLite ...................................................................................... 141 Ray Kiddy ................................................................................................................................................................................. 181 ■Core Data and Hard-Core Design .......................................................................................................................................... 183 Steve Finkelstein ..................................................................................................................................................................... 209 ■Smart In-Application E-mail with Core Data and Three20 ................................................................................................... 211 Florian Pflug and Peter Honeder .............................................................................................................................................. 247 ■How iTap Tackles the Challenges of Networking .................................................................................................................. 249 Jonathan Saggau ..................................................................................................................................................................... 277 ■Fake It ’Til You Make It: Tips and Tricks for Improving Interface Responsiveness .............................................................. 279 Joe Pezzillo .............................................................................................................................................................................. 311 ■Demystifying the Apple Push Notification Service ............................................................................................................... 313 Noel Llopis ............................................................................................................................................................................... 345 ■Environment Mapping and Reflections with OpenGL ES ...................................................................................................... 347 ■Index ..................................................................................................................................................................................... 365 4iv Contents ■Contents at a Glance ............................................................................................................... iv(cid:3) ■Contents .................................................................................................................................. v(cid:3) ■Foreword ................................................................................................................................ xi(cid:3) ■About the Technical Reviewer ............................................................................................... xii ■Preface ................................................................................................................................. xiii Ben Britten Smith ....................................................................................................................... 1(cid:3) ■CHAPTER 1: Everything You Ever Wanted to Know About Particle Systems .................................................................................................... 3(cid:3) Adding Life to Your Game with Particles ..................................................................................................................................................5 Basic Particle Systems and You ...............................................................................................................................................................7 Overview of the Sample Code .............................................................................................................................................................8 Basic Game Flow .................................................................................................................................................................................9 The Anatomy of a Particle System ....................................................................................................................................................10 Code! Finally! ....................................................................................................................................................................................12 Slight Tangent About Degenerates ....................................................................................................................................................15 Back to the Code ...............................................................................................................................................................................16 Random Numbers and Initial Conditions ...........................................................................................................................................19 Emitting Particles ..............................................................................................................................................................................20 Tweaking Your Particle System .............................................................................................................................................................21 May the Force Be with Your Particles ...............................................................................................................................................25 Amazing Technicolor Dream Particle .....................................................................................................................................................28 Off on a Tangent: Lerping ..................................................................................................................................................................28 Color-Changing Particles ...................................................................................................................................................................30 Summary ................................................................................................................................................................................................35 v ■ CONTENTS Joachim Bondo.........................................................................................................................37(cid:3) ■Chapter 2: Chess on the ’Net: Correspondence Gaming with Deep Green................................................................................................39(cid:3) Deep Green, an Already Awesome Application......................................................................................................................................40 The Tasks at Hand..................................................................................................................................................................................42 Inviting a Friend to a Game...............................................................................................................................................................43 Accepting the Invitation....................................................................................................................................................................43 Making a Move..................................................................................................................................................................................43 Getting Notified.................................................................................................................................................................................43 The Tools of the Trade............................................................................................................................................................................44 Stop Talking, Start Coding!....................................................................................................................................................................45 Installing the Tools............................................................................................................................................................................45 Coding the Web Service....................................................................................................................................................................47 Accepting the Challenge on the Device.............................................................................................................................................54 Making a Move..................................................................................................................................................................................57 Summary................................................................................................................................................................................................61 Tom Harrington........................................................................................................................63(cid:3) ■Chapter 3: Audio Streaming: An Exploration into Core Audio...............................................65(cid:3) Hey, I Could Write an App to Play Music................................................................................................................................................66 MPMoviePlayerController: Hey, This Is Easy! Right?..............................................................................................................................66 Finding a Better Approach......................................................................................................................................................................68 The System-Sound Way....................................................................................................................................................................69 AVAudioPlayer: The Not-Available-in-Beta Way................................................................................................................................69 Doing It the Cowboy Way with Core Audio.............................................................................................................................................74 Getting Halfway There: Audio Queue Services..................................................................................................................................74 Getting the Rest of the Way There: Audio File Stream Services........................................................................................................81 Putting It All into an App.........................................................................................................................................................................93 One More Thing.................................................................................................................................................................................93 Launch It!...............................................................................................................................................................................................96 iPhone 3.0 and Further Work.................................................................................................................................................................96 Summary................................................................................................................................................................................................97 Owen Goss................................................................................................................................99(cid:3) ■Chapter 4: You Go Squish Now! Debugging on the iPhone..................................................101(cid:3) Assumed Knowledge............................................................................................................................................................................102 Objective-C vs. C and C++...................................................................................................................................................................104 While You’re Writing That Code............................................................................................................................................................105 Custom Asserts...............................................................................................................................................................................105 Custom Logging..............................................................................................................................................................................107 Using #define..................................................................................................................................................................................108 Crash!...................................................................................................................................................................................................109 Getting a Crash Log from Your Testers...........................................................................................................................................109 You Have Been Saving Your dSYM Files, Right?.............................................................................................................................110 Symbolicatinga Crash Log..............................................................................................................................................................110 6vi ■ CONTENTS Using atos.......................................................................................................................................................................................111 Reproducing Rare Crashes...................................................................................................................................................................112 Thread.............................................................................................................................................................................................112 System............................................................................................................................................................................................113 Race Conditions..............................................................................................................................................................................113 The Scientific Method of Debugging....................................................................................................................................................113 Forming a Hypothesis.....................................................................................................................................................................113 Creating a Test for Your Hypothesis................................................................................................................................................114 Proving or Disproving Your Hypothesis...........................................................................................................................................115 Increasing the Probability of the Crash...........................................................................................................................................115 So, You Have a Call Stack....................................................................................................................................................................115 Starting Code...................................................................................................................................................................................115 What Is a Memory Stomp?..............................................................................................................................................................118 Identifying a Mem Stomp................................................................................................................................................................122 Tools to Detect Memory Problems..................................................................................................................................................123 Watching Variables.........................................................................................................................................................................131 Link Map Files.................................................................................................................................................................................135 Summary..............................................................................................................................................................................................137 Dylan Bruzenak......................................................................................................................139(cid:3) ■Chapter 5: Building Data-Driven Applications with Active Record and SQLite.............................................................................................141(cid:3) A Short Road Off a High Cliff (How I Got Here)....................................................................................................................................141 Ready! Set! Wait, What? (Why I Decided to Write a To-Do Application)...............................................................................................142 Data-Driven Applications on the iPhone...............................................................................................................................................143 Active Record: A Simple Way of Accessing Data................................................................................................................................144 Writing a Database Wrapper Around the C API: ISDatabase................................................................................................................144 Setting Up the Example Project.......................................................................................................................................................145 Creating and Initializing the Database............................................................................................................................................148 Opening a Database Connection.....................................................................................................................................................149 Making Simple Requests.................................................................................................................................................................152 More Advanced SQL.............................................................................................................................................................................158 Preventing Duplicate Create Statements........................................................................................................................................158 Handling Parameters.......................................................................................................................................................................160 Refactoringand Cleanup.................................................................................................................................................................162 Grouping Statements into Transactions..........................................................................................................................................163 Writing a Simple Active Record Layer: ISModel...................................................................................................................................164 Maintaining the Database Connection............................................................................................................................................165 The Model Object: Grocery Item......................................................................................................................................................165 How Groceries Are Mapped.............................................................................................................................................................166 Saving.............................................................................................................................................................................................168 Updating..........................................................................................................................................................................................170 Deleting...........................................................................................................................................................................................170 Finding Grocery Items.....................................................................................................................................................................171 Putting It All Together......................................................................................................................................................................174 vii ■ CONTENTS Simple Migration Handling...................................................................................................................................................................176 Alternative Implementations................................................................................................................................................................179 Summary..............................................................................................................................................................................................180 Ray Kiddy...............................................................................................................................181(cid:3) ■Chapter 6: Core Data and Hard-Core Design.......................................................................183(cid:3) Where Did Core Data Come From?.......................................................................................................................................................184 The Client Is King............................................................................................................................................................................184 A Very First Core Data App...................................................................................................................................................................185 First, Steal Code (Not Music!)..........................................................................................................................................................186 A View to an Object, Any Object......................................................................................................................................................187 Our Very First Crash, or Perhaps Not!.............................................................................................................................................193 CoreData Tutorial for iPhone OS: Managing Model Migrations............................................................................................................194 The Easy Migrations Are Easy.........................................................................................................................................................194 Adding a New Entity........................................................................................................................................................................197 Using Key-Value Coding to Create a Reusable Object..........................................................................................................................199 Remote Databases: It’s All Net!............................................................................................................................................................203 Summary..............................................................................................................................................................................................206 Steve Finkelstein....................................................................................................................209(cid:3) ■Chapter 7: mart In-Application E-mail with Core Data and Three20.................................................................................................211(cid:3) Planning a Simple Offline SMTP Client.................................................................................................................................................212 Creating the User Interface..................................................................................................................................................................213 Diving into Xcode............................................................................................................................................................................213 Setting Up Instance Variables in OfflineMailerAppDelegate.h.........................................................................................................215 Initializing the UIApplication Delegate.............................................................................................................................................217 Working with Core Data.......................................................................................................................................................................218 Understanding the Core Data Stack................................................................................................................................................221 Adding Three20...............................................................................................................................................................................221 Journeying Through the User Interface................................................................................................................................................224 Managing Top-Level Data with DataManager......................................................................................................................................226 Diving into Three20 and TTMessageController....................................................................................................................................228 Composing and Sending Messages.....................................................................................................................................................230 Creating the Core Data Model..............................................................................................................................................................235 Hacking SKPSMTPMessage to Support Threaded Message Sending..................................................................................................239 Setting Up the NSRunLoop on SKPSMTPMessage...............................................................................................................................239 Switching the Bits Back to Online Mode..............................................................................................................................................241 Summary..............................................................................................................................................................................................244 Florian Pflug and Peter Honeder............................................................................................247(cid:3) ■Chapter 8: How iTap Tackles the Challenges of Networking...............................................249(cid:3) Meet iTap and iTap Receiver................................................................................................................................................................250 iTap.................................................................................................................................................................................................251 iTap Receiver...................................................................................................................................................................................251 How the Idea for iTap Emerged and Evolved.......................................................................................................................................252 8viii ■ CONTENTS The Main Challenges............................................................................................................................................................................252 No Physical Buttons on the iPhone.................................................................................................................................................252 Third-Party Applications Cannot Use USB or Bluetooth..................................................................................................................253 Supporting Both Mac and PC..........................................................................................................................................................254 User-Friendliness Demands Autodiscovery of Computers and Devices..........................................................................................255 WiFi Networking on the iPhone from a Programmer’s Perspective.....................................................................................................255 About the Sample Code...................................................................................................................................................................256 Introducing Sockets........................................................................................................................................................................257 Creating a Socket............................................................................................................................................................................258 Using CFSocket to React to Networking Events..............................................................................................................................262 Querying the Network Configuration...............................................................................................................................................264 Contacting All Devices on the Network...........................................................................................................................................267 Detecting WiFi Availability...............................................................................................................................................................268 Playing by the Power Management Rules.......................................................................................................................................269 The Networking Subsystem of iTap.....................................................................................................................................................271 To use Bonjour or Not to Use Bonjour.............................................................................................................................................271 Using Notifications to Communicate Between Components...........................................................................................................272 Our Custom Autodiscovery Solution................................................................................................................................................273 Summary..............................................................................................................................................................................................275 Jonathan Saggau....................................................................................................................277(cid:3) ■Chapter 9: Fake It ’Til You Make It: Tips and Tricks for Improving Interface Responsiveness...........................................................................279(cid:3) Plotting of Historical Stock Prices with AAPLot....................................................................................................................................280 Storing Data Between Runs............................................................................................................................................................283 Using Plists to Persist Data.............................................................................................................................................................284 Saving Data to the iPhone Application Sandbox.............................................................................................................................285 Shipping AAPLot with Placeholder Data...............................................................................................................................................286 Extending the App for Multiple Stock Graphs: StockPlot.....................................................................................................................288 Concurrency.........................................................................................................................................................................................292 NSOperation, NSOperationQueue, and Blocks................................................................................................................................293 Installing the Plausible Blocks Compiler and Adding It to the Project.............................................................................................294 Using Blocks, NSOperation, and NSOperationQueue in StockPlot..................................................................................................295 Displaying Large Amounts of Data Efficiently......................................................................................................................................298 Zooming a UIScrollView.......................................................................................................................................................................300 UIScrollView Zooming Under the Covers.........................................................................................................................................300 Resetting Resolution in a UIScrollView after a Zoom Operation......................................................................................................301 Drawing into an Off-Screen Context....................................................................................................................................................304 Observations, Tips, and Tricks.............................................................................................................................................................309 Summary..............................................................................................................................................................................................310 Joe Pezzillo............................................................................................................................311(cid:3) ■Chapter 10: Demystifying the Apple Push Notification Service...........................................313(cid:3) What Is the Apple Push Notification Service?......................................................................................................................................314 What You’ll Need..................................................................................................................................................................................314 ix ■ CONTENTS Step 1: Create the Client......................................................................................................................................................................314 The Application Delegate................................................................................................................................................................315 Handling Incoming Notifications.....................................................................................................................................................317 Sounds............................................................................................................................................................................................318 Build and Go! Er, Not So Fast..........................................................................................................................................................318 Step 2: Create the Certificate...............................................................................................................................................................319 A Walk-Through of the Program Portal Process..............................................................................................................................319 Back to the Portal............................................................................................................................................................................328 Add the Mobile Provisioning File for Code Signing.........................................................................................................................329 Step 3: Set Up the Server.....................................................................................................................................................................331 A Walk-Through of What This Script Does......................................................................................................................................333 Download Server File......................................................................................................................................................................334 The Home Stretch................................................................................................................................................................................336 Wiring Up the Client........................................................................................................................................................................336 Additional Considerations/Advanced Topics........................................................................................................................................341 Feedback Server.............................................................................................................................................................................341 SSL Server Connections..................................................................................................................................................................342 Moving from Development Sandbox to Production.........................................................................................................................342 Development vs. Ad Hoc.................................................................................................................................................................343 Mobile Provisioning Files................................................................................................................................................................343 Debugging.......................................................................................................................................................................................343 User Experience..............................................................................................................................................................................343 Open Source Code...........................................................................................................................................................................344 Hosted Solutions.............................................................................................................................................................................344 Summary..............................................................................................................................................................................................344 Noel Llopis..............................................................................................................................345(cid:3) ■Chapter 11: Environment Mapping and Reflections with OpenGL ES............................................................................................................347(cid:3) The Beginnings.....................................................................................................................................................................................347 First Steps: OpenGL Lighting................................................................................................................................................................349 Turning to Environment Mapping.........................................................................................................................................................352 Spherical Environment Mapping Implementation................................................................................................................................353 Combining Environment Mapping and Diffuse Textures......................................................................................................................356 Per-Pixel Reflections.......................................................................................................................................................................359 iPhone 3GS......................................................................................................................................................................................362 Summary..............................................................................................................................................................................................363 Index.......................................................................................................................................365 10x