“This book would be a bargain at ten times its price! If you are writing iPhone software, it will save you weeks of development time. Erica has included dozens of crisp and clear examples illustrating essential iPhone development techniques and many others that show special effects going way beyond Apple’s official documentation.”
—Tim Burks, iPhone Software Developer, TootSweet Software
“Erica Sadun’s technical expertise lives up to the Addison-Wesley name. The iPhone Developer’s Cookbook is a comprehensive walkthrough of iPhone development that will help anyone out, from beginners to more experienced developers. Code samples and screenshots help punctuate the numerous tips and tricks in this book.”
—Jacqui Cheng, Associate Editor, Ars Technica
“We make our living writing this stuff and yet I am humbled by Erica’s command of her subject matter and the way she presents the material: pleasantly informal, then very appropriately detailed technically. This is a going to be the Petzold book for iPhone developers.”
—Daniel Pasco, Lead Developer and CEO, Black Pixel Luminance
“The iPhone Developer’s Cookbook should be the first resource for the beginning iPhone programmer, and is the best supplemental material to Apple’s own documentation.”
—Alex C. Schaefer, Lead Programmer, ApolloIM, iPhone Application Development Specialist, MeLLmo, Inc.
“Erica’s book is a truly great resource for Cocoa Touch developers. This book goes far beyond the documentation on Apple’s Web site, and she includes methods that give the developer a deeper understanding of the iPhone OS, by letting them glimpse at what’s going on behind the scenes on this incredible mobile platform.”
—John Zorko, Sr. Software Engineer, Mobile Devices
“I’ve found this book to be an invaluable resource for those times when I need to quickly grasp a new concept and walk away with a working block of code. Erica has an impressive knowledge of the iPhone platform, is a master at describing technical information, and provides a compendium of excellent code examples.”
—John Muchow, 3 Sixty Software, LLC; founder, iPhoneDeveloperTips.com
“This book is the most complete guide if you want coding for the iPhone, covering from the basics to the newest and coolest technologies. I built several applications in the past, but I still learned a huge amount from this book. It is a must-have for every iPhone developer.”
—Roberto Gamboni, Software Engineer, AT&T Interactive
“It’s rare that developer cookbooks can both provide good recipes and solid discussion of fundamental techniques, but Erica Sadun’s book manages to do both very well.”
—Jeremy McNally, Developer, entp
Building Applications with the iPhone 3.0 SDK
Upper Saddle River, NJ • Boston • Indianapolis • San Francisco
New York • Toronto • Montreal • London • Munich • Paris • Madrid
Cape Town • Sydney • Tokyo • Singapore • Mexico City
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals.
The author and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein.
The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact:
U.S. Corporate and Government Sales
(800) 382-3419
[email protected]
For sales outside the United States, please contact:
International Sales
[email protected]
AirPort, App Store, Apple, the Apple logo, Aqua, Bonjour, the Bonjour logo, Cocoa, Cocoa Touch, Cover Flow, Dashcode, Finder, FireWire, iMac, Instruments, Interface Builder, iPhone, iPod, iPod touch, iTunes, the iTunes Logo, Leopard, Mac, Mac logo, Macintosh, Multi-Touch, Objective-C, Quartz, QuickTime, QuickTime logo, Safari, Snow Leopard, Spotlight, and Xcode are trademarks of Apple, Inc., registered in the U.S. and other countries. OpenGL® or OpenGL Logo®: OpenGL is a registered trademark of Silicon Graphics, Inc. The YouTube logo is a trademark of Google, Inc. Intel, Intel Core, and Xeon are trademarks of Intel Corp. in the United States and other countries.
Visit us on the Web: informit.com/aw
Editor-in-Chief
Karen Gettman
Senior Acquisitions Editor
Chuck Toporek
Senior Development Editor
Chris Zahn
Managing Editor
Kristy Hart
Project Editor
Anne Goebel
Copy Editor
Geneil Breeze
Senior Indexer
Cheryl Lenser
Proofreader
Sheri Cain
Technical Reviewers
Joachim Bean,
Aaron Basil,
Tim Isted,
Mr. X,
Tim Burks,
Daniel Pasco,
Alex C. Schaefer,
John Muchow
(3 Sixty Software,
LLC Founder,
iPhoneDeveloperTips.com),
Roberto Gamboni
Editorial Assistant
Romny French
Cover Designer
Gary Adair
Composition
Jake McFarland
Library of Congress Cataloging-in-Publication Data:
Sadun, Erica.
The iPhone developer’s cookbook : building applications with the iPhone 3.0 SDK / Erica
Sadun. — 2nd ed.
p. cm.
Includes index.
ISBN 978-0-321-65957-6 (pbk. : alk. paper) 1. iPhone (Smartphone)—Programming. 2.
Computer software—Development. 3. Mobile computing. I. Title.
QA76.8.I64S33 2010
004.167—dc22
2009042382
Copyright © 2010 Pearson Education, Inc.
All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, write to:
Pearson Education, Inc
Rights and Contracts Department
501 Boylston Street, Suite 900
Boston, MA 02116
Fax (617) 671 3447
ISBN-13: 978-0-321-65957-6
ISBN-10: 0-321-65957-0
Text printed in the United States on recycled paper at Edwards Brothers in Ann Arbor, Michigan.
First printing December 2009
I dedicate this book with love to my husband, Alberto, who has put up with too many gadgets and too many SDKs over the years while remaining both kind and patient at the end of the day.
5 Working with View Controllers
6 Assembling Views and Animations
11 Creating and Managing Table Views
12 Making Connections with GameKit and Bonjour
17 Using Core Location and MapKit
18 Connecting to the Address Book
20 StoreKit: In-App Purchasing
21 Accessibility and Other iPhone OS Services
Understanding Model Differences
Building Hello World the Template Way
Recipe: Using Instruments to Detect Leaks
Recipe: Using Instruments to Monitor Cached Object Allocations
Using the Clang Static Analyzer
From Xcode to Your iPhone: The Organizer Interface
Building for Ad Hoc Distribution
Creating Custom Xcode Templates
One More Thing: Viewing Side-by-Side Code
The Objective-C Programming Language
Methods, Messages, and Selectors
Categories (Extending Classes)
One More Thing: Message Forwarding
Walk-Through: Building a Temperature Converter with IB
Walk-Through: Building a Converter Interface by Hand
Walk-Through: Creating a Hybrid Converter
Walk-Through: Loading .xib Files Directly from Code
One More Thing: A Half Dozen Great Interface Builder Tips
5 Working with View Controllers
Developing with Navigation Controllers
Recipe: Building a Simple Two-Item Menu
Recipe: Adding a Segmented Control
Recipe: Navigating Between View Controllers
Recipe: Using Creative Popping Options
Recipe: Presenting a Custom Modal Information View
One More Thing: Interface Builder and Tab Bar Controllers
6 Assembling Views and Animations
Recipe: Recovering a View Hierarchy Tree
Recipe: Tagging and Retrieving Views
Recipe: Working with View Frames
Recipe: Randomly Moving a Bounded View
Display and Interaction Traits
Recipe: Fading a View In and Out
Recipe: Using Core Animation Transitions
Recipe: General Core Animation Calls
Recipe: Bouncing Views as They Appear
One More Thing: Adding Reflections to Views
Recipe: Finding and Loading Images
Recipe: Accessing Photos from the iPhone Photo Album
Recipe: Selecting and Customizing Images from the Camera Roll
Recipe: Snapping Photos and Writing Them to the Photo Album
Recipe: Saving Pictures to the Documents Folder
Recipe: Capturing Time Lapse Photos
Recipe: Using a Custom Camera Overlay
Recipe: Displaying Images in a Scrollable View
Recipe: Creating a Multiimage Paged Scroll
Recipe: Creating New Images from Scratch
Recipe: Building Thumbnails from Images
Recipe: Working Directly with Bitmaps
One More Thing: Going Grayscale
Recipe: Adding a Simple Direct Manipulation Interface
Recipe: Testing Against a Bitmap
Recipe: Adding Persistence to Direct Manipulation Interfaces
Recipe: Persistence Through Archiving
Recipe: Adding Shake-Controlled Undo Support
One More Thing: Interactive Resize and Rotation
Adding Buttons in Interface Builder
Building Custom Buttons in Xcode
Adding Animated Elements to Buttons
Recipe: Animating Button Responses
Recipe: Adding Custom Slider Thumbs
Recipe: Creating a Twice-Tappable Segmented Control
Recipe: Dismissing a UITextField Keyboard
Recipe: Dismissing UITextView Keyboards
Recipe: Building a Better Text Editor
Recipe: Adding a Page Indicator Control
Recipe: Creating a Customizable Paged Scroller
Talking Directly to Your User Through Alerts
Recipe: Creating Modal Alerts with Run Loops
Recipe: Soliciting Text Input from the User
Recipe: Using Variadic Arguments with Alert Views
Recipe: Presenting Simple Menus
Recipe: Displaying Text in Action Sheets
“Please Wait”: Showing Progress to Your User
Recipe: Building a UIProgressView
Recipe: Building Custom Overlays
Recipe: Orientable Scroll-Down Alerts
Recipe: Using the Network Activity Indicator
One More Thing: Showing the Volume Alert
11 Creating and Managing Table Views
Introducing UITableView and UITableViewController
Recipe: Implementing a Very Basic Table
Recipe: Changing a Table’s Background Color
Recipe: Creating a Table Image Backsplash
Recipe: Building Custom Cells in Interface Builder
Recipe: Alternating Cell Colors
Recipe: Building a Custom Cell with Built-In Controls
Recipe: Remembering Control State for Custom Cells
Recipe: Creating Checked Table Cells
Recipe: Removing Selection Highlights from Cells
Recipe: Working with Disclosure Accessories
Recipe: Adding Undo Support to a Table
Recipe: Searching Through a Table
Recipe: Creating Grouped Tables
Recipe: Customizing Headers and Footers
Recipe: Creating a Group Table with Many Cell Types and Heights
Recipe: Building a Multiwheel Table
Recipe: Using a View-Based Picker
Recipe: Using the UIDatePicker
One More Thing: Formatting Dates
12 Making Connections with GameKit and Bonjour
Recipe: Creating Basic GameKit Services
Recipe: Peeking Behind the Scenes
Recipe: Sending Complex Data Through GameKit
Recipe: Using Bonjour to Create an iPhone Server
Recipe: Creating a Mac Client for an iPhone Bonjour Service
Recipe: Working Around Real-World GameKit Limitations
Recipe: iPhone to iPhone Gaming Via BonjourHelper
Creating an “Online” GameKit Connection
One More Thing: Scanning for Services
Recipe: Checking Your Network Status
Recipe: Extending the UIDevice Class for Reachability
Recipe: Scanning for Connectivity Changes
Recipe: Recovering IP and Host Information
Recipe: Checking Site Availability
Recipe: Asynchronous Downloads
Recipe: Handling Authentication Challenges
Recipe: Using the Keychain to Store Sensitive Data
Recipe: Sharing Keychains Between Applications
Recipe: Converting XML into Trees
Recipe: Building a Simple Web-Based Server
Recipe: Accessing Core Device Information
Adding Device Capability Restrictions
Recipe: Recovering Additional Device Information
Recipe: Monitoring the iPhone Battery State
Recipe: Enabling and Disabling the Proximity Sensor
Recipe: Using Acceleration to Locate “Up”
Recipe: Using Acceleration to Move Onscreen Objects
Recipe: Detecting Device Orientation
Recipe: Detecting Shakes Using Motion Events
Recipe: Detecting Shakes Directly from the Accelerometer
One More Thing: Checking for Available Disk Space
Recipe: Playing Audio with AVAudioPlayer
Recipe: Handling Audio Interruptions
Recipe: Audio That Ignores Sleep
Recipe: Recording Audio with Audio Queues
Recipe: Playing Video with the Media Player
Recipe: Picking and Editing Video
Recipe: Picking Audio with the MPMediaPickerController
Recipe: Using the MPMusicPlayerController
One More Thing: Additional Movie Player Properties
Introducing Push Notifications
Building Notification Payloads
17 Using Core Location and MapKit
Recipe: Core Location in a Nutshell
Recipe: Computing Speed and Distance
Recipe: Keeping Track of “North” by Using Heading Values
Recipe: User Location Annotations
Recipe: Creating Map Annotations
18 Connecting to the Address Book
Recipe: Working with the Address Book
Recipe: Searching the Address Book
Recipe: Limiting Contact Picker Properties
Recipe: Modifying Existing Contacts
Recipe: The ABUnknownPersonViewController
One More Thing: Adding Random Contact Art
Recipe: Using Core Data for a Table Data Source
Recipe: Search Tables and Core Data
Recipe: Integrating Core Data Tables with Live Data Edits
Recipe: Implementing Undo-Redo Support with Core Data
20 StoreKit: In-App Purchasing
Creating New In-App Purchase Items
21 Accessibility and Other iPhone OS Services
Adding VoiceOver Accessibility to Your Apps
Recipe: Adding Custom Settings Bundles
Recipe: Creating URL-Based Services
This book would not exist without the efforts of Chuck Toporek (my editor and whip-cracker), Chris Zahn (the awesomely talented development editor), Romny French (the faithful and rocking editorial assistant who kept things rolling behind the scenes), and to Karen Gettman (Chuck’s Editor-in-Chief) for her continued support of this ever-growing (and I do mean growing—just check out the page count) book. Also, a big thank you to the entire Addison-Wesley/Pearson production team, specifically Kristy Hart, Anne Goebel, Gary Adair, Keith Cline, Geneil Breeze, Cheryl Lenser, Chelsey Marti, and Jake McFarland. Thanks also to the crew at Safari for getting my book up in Rough Cuts and for quickly fixing things when technical glitches occurred.
Thanks go as well to Neil Salkind, my agent of many years, to the tech reviewers who helped keep this book in the realm of sanity rather than wishful thinking, and to all my colleagues, both present and former, at TUAW, Ars Technica, and the Digital Media/Inside iPhone blog.
Special thanks go to Joachim Bean and Aaron Basil. In addition to tech reviewing this book, these two men provided early feedback as I was developing each chapter, offering critical insight and advice. More than anyone else, they helped shape the book you now hold in your hands. They delivered a level of feedback that was both astonishing, and deeply, deeply appreciated, even when queried at inhuman hours of the day. Thanks also to Tim Isted (author of Core Data for iPhone, coming soon from Addison-Wesley), for his valuable input on the Core Data chapter in this book. I’d also like to thank someone for placing some keen eyes on the GameKit chapter, but I can’t, so I’ll just have to say, “Thanks, Mr. X.” I couldn’t have done this without the help of my technical review team, so thank you all very much. Special thanks to the rest of my technical review team including Roberto Gamboni, John Muchow, and Scott Mikolaitis.
I am deeply indebted to the wide community of iPhone developers, including Alex Schaefer, Nick Penree, James Cuff, Jay Freeman, Mark Montecalvo, August Joki, Max Weisel, Optimo, Kevin Brosius, Planetbeing, Pytey, Roxfan, MuscleNerd, np101137, UnterPerro, Youssef Francis, Bryan Henry, Daniel Peebles, ChronicProductions, Greg Hartstein, Emanuele Vulcano, Sean Heber, Steven Troughton-Smith, Dick Applebaum, Kevin Ballard, Jay Abbott, Tim Grant Davies, Landon Fuller, Stefan Hafeneger, Scott Elich, chrallelinder, J. Roman, jtbandes, Artissimo, Aaron Alexander, Scott Lawrence, Kenny Chan Ching-Kin, Sjoerd van Geffen, Absentia, Nownot, Matt Brown, Chris Foresman, Aron Trimble, Paul Griffin, Nicolas Haunold, Anatol Ulrich (hypnocode GmbH), Kristian Glass, Yanik Magnan, ashikase, Eric Mock, and everyone at the iPhone developer channels at irc.saurik.com and irc.freenode.net, among many others too numerous to name individually. Their techniques, suggestions, and feedback helped make this book possible. If I have overlooked anyone who helped contribute, please accept my apologies for the oversight.
Special thanks go out to my family and friends, who supported me through month after month of new beta releases and who patiently put up with my unexplained absences and frequent howls of despair. I appreciate you all hanging in there with me. And thanks to my children for their steadfastness, even as they learned that a hunched back and the sound of clicking keys is a pale substitute for a proper mother. My kids provided invaluable assistance over the last few months by testing applications, offering suggestions, and just being awesome people. I am such an insanely lucky mom that these kids are part of my life.
Erica Sadun has written, coauthored, and contributed to about three dozen books on technology, particularly in the areas of programming, digital video, and digital photography. An unrepentant geek, Sadun has never met a gadget she didn’t need. Her checkered past includes run-ins with NeXT, Newton, iPhone, and myriad successful and unsuccessful technologies. When not writing, she and her geek husband parent three adorable geeks-in-training, who regard their parents with restrained bemusement.
Few platforms match the iPhone’s unique developer technologies. The iPhone combines OS X-based mobile computing with an innovative multitouch screen, location awareness, an onboard accelerometer, and more. When Apple first introduced the iPhone SDK beta in March 2008, developers responded in droves, bringing Apple’s servers to its knees. In less than a week, developers downloaded the iPhone SDK more than 100,000 times.
Since then, more than 50,000 applications have been delivered to the App Store for an audience that now exceeds 30 million iPhones and more than 20 million iPod touches. As the iPhone ecosystem continues to grow, The iPhone Developer’s Cookbook will continue to evolve as an accessible resource for those new to iPhone programming.
If you purchased the first edition of this book, you might ask yourself, Why do I need to buy the new edition, too? The answer is pretty simple: Just compare the size of the two books. This new edition is more than 200% larger than the original edition. That’s right, we’ve packed on almost 500 pages of new material so we could cover everything that’s new to the iPhone 3.0 SDK, as well as expand on some of the topics covered in the first edition.
Some things you’ll find new to this edition include chapters or coverage on
• How to use Xcode and Interface Builder
• An Objective-C jump-start tutorial
• Core Data for the iPhone
• MapKit and Core Location
• Using GameKit beyond games to add chat and Bonjour networking
• Advanced motion detection including shake-to-undo support
• The new search display controller class, along with custom table headers and footers
• Apple’s new device capabilities specifications
• In-App purchasing with StoreKit
• Push notification, both from the client and server side
• Searching for and playing media from the onboard iPod library
• Video capture and editing, plus the new AV audio player and recorder classes
• How to leverage the Accessibility framework, including VoiceOver, in your app
• And much, much more!
You’ll also notice that we’ve taken your feedback to heart. When the first edition came out, there was some confusion about who the target audience was for this book. Was it for new developers or experienced developers? Well, we’ve taken care of that, too. While this book is for experienced iPhone and Mac developers already familiar with Objective-C, Xcode, and the Cocoa frameworks, this new edition includes an “Objective-C Boot Camp” (see Chapter 3), and coverage of Xcode and Interface Builder, to help developers who have experience working in other languages (or on other platforms) quickly get oriented into the Mac/iPhone world.
While it is true that one book can’t be everything to everyone, we’re certainly giving it a shot in this new edition. We hope you like the changes you see throughout this bigger book, and if you do, be sure to post a review on Amazon or send me a note ([email protected]).
This book is written for experienced developers who want to build apps for the iPhone and iPod touch. You should already be familiar with Objective-C, the Cocoa frameworks, and the Xcode Tools. That said, if you’re new to the platform, this new edition of The iPhone Developer’s Cookbook includes a quick-and-dirty introduction to Objective-C, along with an intro to the Xcode Tools, to help you quickly get up to speed.
If you have some C experience, or have spent some time with another object-oriented language such as C++ or Java, we included a section in this Preface to help guide you down the road to being a Mac developer. Be sure to read the section “Your Roadmap to Mac/iPhone Development,” later in this Preface.
Although each programmer brings different goals and experiences to the table, most iPhone developers end up solving similar tasks in their development work:
• “How do I build a table?”
• “How do I create a secure Keychain entry?”
• “How do I search the Address Book?”
• “How do I move between views?”
• “How do I use Core Location and the iPhone 3GS’s magnetometer?”
And so on. If you’ve asked yourself these questions, then this book is for you. Complete with clear, fully documented examples, The iPhone Developer’s Cookbook will get you up to speed and working with the iPhone SDK in no time. Best of all, all of the code recipes in the book have been tested—and put to the test in real-world applications—offering you ready-to-use solutions for the apps you’re building today.
It goes without saying that, if you’re planning to build apps for the iPhone or iPod touch, you’re going to need at least one of those devices to test out your application. The following list covers the basics of what you need to begin programming for the iPhone or iPod touch:
• Apple’s iPhone SDK—The latest version of the iPhone SDK can be downloaded from Apple’s iPhone Dev Center (http://developer.apple.com/iphone). You must join Apple’s (free) developer program before you download; however, if you plan to sell apps through the App Store, you will need to become a paid iPhone developer, which costs $99/year for individuals and $299/year for enterprise (i.e., corporate) developers. Registered developers receive certificates that allow them to “sign” and download their applications to their iPhone/iPod touch for testing and debugging.
Apple also offers a University program for students and educators. If you are a CS student taking classes at the university level, check with your professor to see if your school is part of the University Program. For more information about the iPhone Developer University Program, see http://developer.apple.com/support/iphone/university.
• An Intel-based Mac running Mac OS X Leopard or Snow Leopard—Snow Leopard is recommended, as it offers access to Xcode 3.2 with its many new features like “Build and Analyze.” You need plenty of disk space for development, and your Mac should have at least 1GB RAM, preferably 2GB or 4GB to help speed up compile time.
• An iPhone or iPod touch—Although the iPhone SDK and Xcode include a simulator for you to test your applications in, you really do need to have an actual iPhone and/or iPod touch if you’re going to develop for the platform. You can use the USB cable to tether your unit to the computer and install the software you’ve built. For real-life App Store deployment, it helps to have several units on-hand, representing the various hardware generations, so you can test on the same platforms your target audience will use.
• At least one available USB 2.0 port—This enables you to tether a development iPhone or iPod touch to your computer for file transfer and testing.
• An Internet connection—This connection enables you to test your programs with a live Wi-Fi connection as well as with an EDGE or 3G service.
• Familiarity with Objective-C—To program for the iPhone, you need to know Objective-C 2.0. The language is based on ANSI C with object-oriented extensions, which means you also need to know a bit of C, too. If you have programmed with Java or C++ and are familiar with C, making the move to Objective-C is pretty easy. Chapter 3, “Objective-C Boot Camp,” helps you get up to speed.
Although the SDK supports development for the iPhone and iPod touch, as well as possible yet-to-be-announced platforms, this book refers to the target platform as iPhone for the sake of simplicity. When developing for the iPod touch, most of the examples in this book are applicable; however, certain features such as telephony and onboard speakers are not applicable to the iPod touch.
As mentioned earlier, one book can’t be everything to everyone. And try as I might, if we were to pack everything you’d need to know into this book, you wouldn’t be able to pick it up. There is, indeed, a lot you need to know to develop for the Mac and iPhone platforms. If you are just starting out and don’t have any programming experience, your first course of action should be to take a college-level course in the C programming language. While the alphabet might start with the letter A, the root of most programming languages, and certainly your path as a developer, is C.
Once you know C and how to work with a compiler (something you’ll learn in that basic C course), the rest should be easy. From there, you’ll hop right on to Objective-C and learn how to program with that alongside the Cocoa frameworks. To help you along the way, I’ve put together the flowchart shown in Figure P-1 to point you at some books of interest.
Once you know C, you’ve got a few options for learning how to program with Objective-C. For a quick-and-dirty overview of Objective-C, you can turn to Chapter 3 of this book and read the Objective-C Boot Camp. However, if you want a more in-depth view of the language, you can either read Apple’s own documentation, Object-Oriented Programming with Objective-C 2.0,1 or you can opt to buy a book such as Stephen Kochan’s Programming in Objective-C 2.0 (Addison-Wesley, 2009).
1 See http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/OOP_ObjC/OOP_ObjC.pdf.
With the language behind you, next up is tackling Cocoa and the developer tools, otherwise known as Xcode. For that, you have a few different options. Again, you can refer to Apple’s own documentation on Cocoa and Xcode,2 or if you prefer books, you can learn from the best. Aaron Hillegass, founder of the Big Nerd Ranch in Atlanta,3 is the author of Cocoa Programming for Mac OS X, now in its third edition. Aaron’s book is highly regarded in Mac developer circles and is the most-recommended book you’ll see on the cocoa-dev mailing list. To learn more about Xcode, look no further than Fritz Anderson’s Xcode 3 Unleashed from Sams Publishing. While the current edition doesn’t cover iPhone-specific features of Xcode (which were introduced with Xcode 3.1), the book will give you a solid grounding in how to use Xcode as your development environment.
2 See the Cocoa Fundamentals Guide (http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaFundamentals.pdf) for a head start on Cocoa, and for Xcode, see A Tour of Xcode (http://developer.apple.com/mac/library/documentation/DeveloperTools/Conceptual/A_Tour_of_Xcode/A_Tour_of_Xcode.pdf).
3 Big Nerd Ranch: http://www.bignerdranch.com.
There are plenty of other books from other publishers on the market, including the best-selling Beginning iPhone 3 Development, by Dave Marks and Jeff LaMarche (Apress, 2009), so don’t just limit yourself to one book or publisher.
To truly master Mac development, you need to look at a variety of sources: books, blogs, mailing lists, Apple’s own documentation, and, best of all, conferences. If you get the chance to attend WWDC or C4, you’ll know what I’m talking about. The time you spend at those conferences talking with other developers and in the case of WWDC, talking with Apple’s engineers, is well worth the expense if you are a serious developer.
This book offers single-task recipes for the most common issues new iPhone developers face: laying out interface elements, responding to users, accessing local data sources, and connecting to the Internet. Each chapter groups related tasks together, allowing you to jump directly to the solution you’re looking for without having to decide which class or framework best matches that problem.
The iPhone Developer’s Cookbook offers you “cut-and-paste convenience,” which means you can freely reuse the source code from recipes in this book for your own applications and then tweak the code to suit your app’s needs.
Here’s a rundown of what you find in this book’s chapters:
• Chapter 1, “Introducing the iPhone SDK”—Chapter 1 introduces the iPhone SDK and explores the iPhone as a delivery platform, limitations and all. It explains the breakdown of the standard iPhone application and helps you get started with the iPhone Developer Portal.
• Chapter 2, “Building Your First Project”—Chapter 2 covers the basics for building your first Hello World-style applications. It introduces Xcode and Interface Builder, showing how you can use these tools in your projects. You read about basic debugging tools, walk through using them, and pick up some tips about handy compiler directives. You’ll also discover how to create provisioning profiles and use them to deploy your application to your device, to beta testers, and to App Store.
• Chapter 3, “Objective-C Boot Camp”—If you’re new to Objective-C as well as to the iPhone, you’ll appreciate this basic skills chapter. Objective-C is the standard programming language for both the iPhone and for Mac OS X. It offers a powerful object-oriented language that lets you build applications that leverage Apple’s Cocoa and Cocoa Touch frameworks. Chapter 3 introduces the language, provides an overview of its object-oriented features, discusses memory management skills, and adds a common class overview to get you started with Objective-C programming.
• Chapter 4, “Designing Interfaces”—Chapter 4 introduces the iPhone’s library of visual classes. It surveys these classes and their geometry. In this chapter, you learn how to work with these visual classes and discover how to handle tasks like device reorientation. You’ll read about solutions for laying out and customizing interfaces and learn about hybrid solutions that rely both on Interface Builder-created interfaces and Objective-C-centered ones.
• Chapter 5, “Working with View Controllers”—The iPhone paradigm in a nutshell is this: small screen, big virtual worlds. In Chapter 5, you discover the various view controller classes that enable you to enlarge and order the virtual spaces your users interact with. You learn how to let these powerful objects perform all the heavy lifting when navigating between iPhone application screens.
• Chapter 6, “Assembling Views and Animations”—Chapter 6 introduces iPhone views, objects that live on your screen. You see how to lay out, create, and order your views to create backbones for your iPhone applications. You read about view hierarchies, geometries, and animations, features that bring your iPhone applications to life.
• Chapter 7, “Working with Images”—Chapter 7 introduces images, specifically the UIImage
class, and teaches you all the basic know-how you need for working with iPhone images. You learn how to load, store, and modify image data in your applications. You see how to add images to views and how to convert views into images. And you discover how to process image data to create special effects, how to access images on a byte-by-byte basis, and how to take photos with your iPhone’s built-in camera.
• Chapter 8, “Gestures and Touches”—On the iPhone, the touch provides the most important way that users communicate their intent to an application. Touches are not limited to button presses and keyboard interaction. Chapter 8 introduces direct manipulation interfaces, multitouch, and more. You see how to create views that users can drag around the screen and read about distinguishing and interpreting gestures.
• Chapter 9, “Building and Using Controls”—Control classes provide the basis for many of the iPhone’s interactive elements, including buttons, text fields, sliders, and switches. This chapter introduces controls and their use. You read about standard control interactions and how to customize these objects for your application’s specific needs. You even learn how to build your own controls from the ground up, as Chapter 9 creates a custom touch wheel.
• Chapter 10, “Alerting Users”—The iPhone offers many ways to provide users with a heads-up, from pop-up dialogs and progress bars to audio pings and status bar updates. Chapter 10 shows how to build these indications into your applications and expand your user-alert vocabulary. It introduces standard ways of working with these pop-up classes and offers solutions that allow you to craft more linear programs without explicit callbacks.
• Chapter 11, “Creating and Managing Table Views”—Tables provide a scrolling interaction class that works particularly well on a small, cramped device. Many, if not most, apps that ship with the iPhone and iPod touch center on tables, including Settings, YouTube, Stocks, and Weather. Chapter 11 shows how iPhone tables work, what kinds of tables are available to you as a developer, and how you can use table features in your own programs.
• Chapter 12, “Making Connections with GameKit and Bonjour”—GameKit is Apple’s new ad hoc networking solution for peer-to-peer connectivity. It’s built on a technology called Bonjour that offers simple, no-configuration communications between devices. Chapter 12 introduces GameKit, allowing you to build games and utilities that move information back and forth between iPhones or between an iPhone and a desktop system. This chapter covers standard GameKit, introduces GameKit Voice for walkie-talkie-style voice chats, and offers some basic Bonjour programming that extends beyond GameKit limitations, allowing you to expand your iPhone communications to the desktop.
• Chapter 13, “Networking”—As an Internet-connected device, the iPhone is particularly suited to subscribing to Web-based services. Apple has lavished the platform with a solid grounding in all kinds of network computing services and their supporting technologies. Chapter 13 surveys common techniques for network computing and offering recipes that simplify day-to-day tasks. You read about network reachability, synchronous and asynchronous downloads, working with the iPhone’s secure keychain to meet authentication challenges, and more.
• Chapter 14, “Device Capabilities”—Each iPhone device represents a meld of unique, shared, momentary, and persistent properties. These properties include the device’s current physical orientation, its model name, battery state, and access to onboard hardware. Chapter 14 looks at the device from its build configuration to its active onboard sensors. It provides recipes that return a variety of information items about the unit in use. You read about testing for hardware prerequisites at runtime and specifying those prerequisites in the application’s Info.plist file. You discover how to solicit sensor feedback and subscribe to notifications to create callbacks when those sensor states change. This chapter covers the hardware, file system, and sensors available on the iPhone device and helps you programmatically take advantage of those features.
• Chapter 15, “Audio, Video, and MediaKit”—The iPhone is a media master; its built-in iPod features expertly handle both audio and video. The iPhone SDK exposes that functionality to developers. A rich suite of classes simplifies media handling via playback, search, and recording. Chapter 15 introduces recipes that use these classes, presenting media to your users and letting your users interact with that media. You see how to build audio and video players as well as audio and video recorders. You discover how to browse the iPod library and how to choose what items to play.
• Chapter 16, “Push Notifications”—When developers need to communicate directly with users, push notifications provide the solution. They deliver messages directly to the iPhone screen via a special Apple service. Push notifications let the iPhone display an alert, play a custom sound, or update an application badge. In this way, off-phone services connect with an iPhone-based client, letting them know about new data or updates. Chapter 16 introduces push notifications. In this chapter, you learn how push notifications work and dive into the details needed to create your own push-based system.
• Chapter 17, “Using Core Location and MapKit”—Core Location infuses the iPhone with on-demand geopositioning based on a variety of technologies and sources. MapKit adds interactive in-application mapping allowing users to view and manipulate annotated maps. With Core Location and MapKit, you can develop applications that help users meet up with friends, search for local resources, or provide location-based streams of personal information. Chapter 17 introduces these location-aware frameworks and shows you how you can integrate them into your iPhone applications.
• Chapter 18, “Connecting to the Address Book”—The iPhone’s Address Book frameworks allow you to programmatically access and manage the contacts database. Chapter 18 introduces the Address Book and demonstrates how to use its frameworks in your applications. You read about accessing information on a contact-by-contact basis, how to modify and update contact information, and how to use predicates to find just the contact you’re interested in. This chapter also covers the GUI classes that provide interactive solutions for picking, viewing, and modifying contacts.
• Chapter 19, “A Taste of Core Data”—Core Data offers managed data stores that can be queried and updated from your application. It provides a Cocoa Touch-based object interface that brings relational data management out from SQL queries and into the Objective-C world of iPhone development. Chapter 19 introduces Core Data. It provides just enough recipes to give you a taste of the technology, offering a jumping off point for further Core Data learning. You learn how to design managed database stores, add and delete data, and query that data from your code.
• Chapter 20, “StoreKit: In-App Purchasing”—New to the 3.0 SDK, StoreKit offers in-app purchasing that integrates into your software. This chapter introduces StoreKit and shows you how to use the StoreKit API to create purchasing options for users. In this chapter, you read about getting started with StoreKit. You learn how set up products at iTunes Connect and localize their descriptions. And you see what it takes to create test users and how to work your way through various development/deployment hurdles. This chapter teaches you how to solicit purchase requests from users and how to hand over those requests to the store for payment. This chapter covers the entire StoreKit picture, from product creation to sales.
• Chapter 21, “Accessibility and Other iPhone OS Services”—Applications interact with standard iPhone services in a variety of ways. This chapter explores some of these approaches. Applications can define their interfaces to the iPhone’s VoiceOver accessibility handler, creating descriptions of their GUI elements. They can create bundles to work with the built-in Settings applications so that users can access applications defaults using that interface. Applications can also declare public URL schemes allowing other iPhone applications to contact them and request services that they themselves offer. This chapter explores application service interaction. It shows you how you implement these features in your applications. You see how to build these service bridges through code, through Interface Builder, and through supporting files.
• Appendix A, “Info.plist Keys”—This appendix gathers together many of the keys available for the iPhone’s Info.plist file, the file that describes an application to the iPhone operating system.
For the sake of pedagogy, this book’s sample code usually presents itself in a single main.m file. This is not how people normally develop iPhone or Cocoa applications, or should be developing them, but it provides a great way of presenting a single big idea. It’s hard to tell a story when readers must look through 5 or 7 or 9 individual files at once. Offering a single file concentrates that story, allowing access to that idea in a single chunk.
These samples are not intended as stand-alone applications. They are there to demonstrate a single recipe and a single idea. One main.m file with a central presentation reveals the implementation story in one place. Readers can study these concentrated ideas and transfer them into normal application structures, using the standard file structure and layout. The presentation in this book does not produce code in a standard day-to-day best practices approach. Instead, it reflects a pedagogical approach that offers concise solutions that you can incorporate back into your work as needed.
Contrast that to Apple’s standard sample code, where you must comb through many files to build up a mental model of the concepts that are on offer. Those samples are built as full applications, often doing tasks that are related to but not essential to what you need to solve. Finding just those relevant portions is a lot of work. The effort may outweigh any gains. In this book, there are two exceptions to this one-file rule:
• First, application-creation walkthroughs use the full file structure created by Xcode to mirror the reality of what you’d expect to build on your own. The walk-through folders may therefore contain a dozen or more files at once.
• Second, standard class and header files are provided when the class itself is the recipe or provides a precooked utility class. Instead of highlighting a technique, some recipes offer these precooked class implementations and categories (that is, extensions to a preexisting class rather than a new class). For those recipes, look for separate .m and .h files in addition to the skeletal main.m that encapsulates the rest of the story.
For the most part, the samples for this book use a single application identifier, com.sadun.helloworld. You need to replace this identifier with one that matches your provision profile. This book uses one identifier to avoid clogging up your iPhone with dozens of samples at once. Each sample replaces the previous one, ensuring that SpringBoard remains relatively uncluttered. If you want to install several samples at once, simply edit the identifier, adding a unique suffix, such as com.sadun.helloworld.table-edits.
The source code for this book can be found at the open source GitHub hosting site at http://github.com/erica/iphone-3.0-cookbook-/tree. There, you find a chapter-by-chapter collection of source code that provides working examples of the material covered in this book.
Sample code is never a fixed target. It continues to evolve as Apple updates its SDK and the Cocoa Touch libraries. Get involved. You can pitch in by suggesting bug fixes and corrections as well as by expanding the code that’s on offer. GitHub allows you to fork repositories and grow them with your own tweaks and features, and share those back to the main repository. If you come up with a new idea or approach, let us know. We’d be happy to include great suggestions both at the repository and in the next edition of this Cookbook.
You can download this Cookbook’s source code using the git version control system. A Mac OS X implementation of git is available at http://code.google.com/p/git-osx-installer. Mac OS X git implementations include both command line and GUI solutions, so hunt around for the version that best suits your development needs.
GitHub (http://github.com) is the largest git hosting site, with more than 150,000 public repositories. It provides both free hosting for public projects and paid options for private projects. With a custom Web interface that includes wiki hosting, issue tracking, and an emphasis on social networking of project developers, it’s a great place to find new code or collaborate on existing libraries. You can sign up for a free account at their Web site, allowing you to copy and modify the Cookbook repository or create your own open source iPhone projects to share with others.
If you have any comments or questions about this book, please drop me an e-mail message at [email protected], or stop by www.ericasadun.com for updates about the book and news for iPhone developers. Please feel free to visit, download software, read documentation, and leave your comments.
52.15.233.135