HOUR 1 Preparing your System and iPhone for Development 2 Introduction to Xcode and the iPhone Simulator 3 Discovering Objective-C: The Language of Apple Platforms 4 Inside Cocoa Touch 5
Trang 2800 East 96th Street, Indianapolis, Indiana, 46240 USA
Sams Teach Yourself
Trang 3All rights reserved No part of this book shall be reproduced, stored in a retrieval system, or
transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without
written permission from the publisher No patent liability is assumed with respect to the use of
the information contained herein Although every precaution has been taken in the preparation of
this book, the publisher and author assume no responsibility for errors or omissions Nor is any
liability assumed for damages resulting from the use of the information contained herein
1 iPhone (Smartphone)—Programming 2 Application software—Development I Title II Title:
Teach yourself iPhone application development in 24 hours III Title: iPhone application
develop-ment in 24 hours
QA76.8.I64R39 2011
005.26—dc22
2010035798Printed in the United States of America
First Printing October 2010
Trademarks
All terms mentioned in this book that are known to be trademarks or service marks have been
appropriately capitalized Sams Publishing cannot attest to the accuracy of this information Use
of a term in this book should not be regarded as affecting the validity of any trademark or service
mark
Warning and Disclaimer
Every effort has been made to make this book as complete and as accurate as possible, but no
warranty or fitness is implied The information provided is on an “as is” basis The author and the
publisher shall have neither liability nor responsibility to any person or entity with respect to any
loss or damages arising from the information contained in this book
Bulk Sales
Sams Publishing offers excellent discounts on this book when ordered in quantity for bulk
pur-chases or special sales For more information, please contact
U.S Corporate and Government Sales
Keith Cline
Managing Editor
Sandra Schroeder
Senior ProjectEditor
Technical Editor
Matthew David
PublishingCoordinator
Trang 4HOUR 1 Preparing your System and iPhone for Development
2 Introduction to Xcode and the iPhone Simulator
3 Discovering Objective-C: The Language of Apple Platforms
4 Inside Cocoa Touch
5 Exploring Interface Builder
6 Model-View-Controller Application Design
7 Working with Text, Keyboards, and Buttons
8 Handling Images, Animation, and Sliders
9 Using Advanced Interface Objects and Views
10 Getting the User’s Attention
11 Making Multivalue Choices with Pickers
12 Implementing Multiple Views with Toolbars and Tab Bars
13 Displaying and Navigating Data Using Table Views
14 Reading and Writing Application Data
15 Building Rotatable and Resizable User Interfaces
16 Using Advanced Touches and Gestures
17 Sensing Orientation and Motion
18 Working with Rich Media
19 Interacting with Other Applications
20 Implementing Location Services
21 Building Background-aware Applications
22 Building Universal Applications
23 Application Debugging and Optimization
24 Distributing Applications Through the App Store
Index
Trang 5Introduction 1
Who Can Become an iPhone Developer? .1
Who Should Use This Book? .2
What Is (and Isn’t) in This Book? .2
HOUR 1: Preparing Your System and iPhone for Development 3 Welcome to the iOS Platform .3
Becoming an iOS Developer .7
Creating a Development Provisioning Profile .12
Developer Technology Overview .23
Summary .25
Q&A .25
Workshop .26
HOUR 2:Introduction to Xcode and the iPhone Simulator 27 Using Xcode .27
Using the iPhone Simulator .45
Further Exploration .50
Summary .50
Q&A .51
Workshop .51
HOUR 3: Discovering Objective-C: The Language of Apple Platforms 53 Object-Oriented Programming and Objective-C .53
Exploring the Objective-C File Structure .58
Objective-C Programming Basics .64
Memory Management .74
Further Exploration .77
Summary .77
Q&A .78
Workshop .79
Trang 6Exploring the iOS Technology Layers .83
Tracing the iPhone Application Life Cycle .88
Cocoa Fundamentals .90
Exploring the iOS Frameworks with Xcode .98
Summary .102
Q&A .102
Workshop .103
HOUR 5: Exploring Interface Builder 105 Understanding Interface Builder .105
Creating User Interfaces .110
Customizing Interface Appearance .115
Connecting to Code .119
Further Exploration .126
Summary .127
Q&A .127
Workshop .128
HOUR 6: Model-View-Controller Application Design 129 Understanding the Model-View-Controller Paradigm .129
How Xcode and Interface Builder Implement MVC .131
Using the View-Based Application Template .135
Further Exploration .148
Summary .149
Q&A .149
Workshop .150
HOUR 7: Working with Text, Keyboards, and Buttons 151 Basic User Input and Output .151
Using Text Fields, Text Views, and Buttons .153
Setting Up the Project .154
Further Exploration .176
Trang 7Summary .177
Q&A .177
Workshop .178
HOUR 8: Handling Images, Animation, and Sliders 179 User Input and Output .179
Creating and Managing Image Animations and Sliders .181
Further Exploration .196
Summary .197
Q&A .197
Workshop .198
HOUR 9: Using Advanced Interface Objects and Views 199 User Input and Output (Continued) .199
Using Switches, Segmented Controls, and Web Views .204
Using Scrolling Views .221
Further Exploration .227
Summary .227
Q&A .228
Workshop .228
HOUR 10:Getting the User’s Attention 231 Exploring User Alert Methods .231
Generating Alerts .235
Using Action Sheets .245
Using Alert Sounds and Vibrations .249
Further Exploration .253
Summary .254
Q&A .254
Workshop .255
HOUR 11:Making Multivalue Choices with Pickers 257 Understanding Pickers .257
Using Date Pickers .261
Trang 8Implementing a Custom Picker View .270
Further Exploration .289
Summary .290
Q&A .290
Workshop .291
HOUR 12: Implementing Multiple Views with Toolbars and Tab Bars 293 Exploring Single Versus Multi-View Applications .293
Creating a Multi-View Toolbar Application .295
Building a Multi-View Tab Bar Application .307
Further Exploration .326
Summary .327
Q&A .327
Workshop .328
HOUR 13: Displaying and Navigating Data Using Table Views 329 Understanding Table Views and Navigation Controllers .329
Building a Simple Table View Application .332
Creating a Navigation-Based Application .344
Further Exploration .359
Summary .359
Q&A .360
Workshop .360
HOUR 14: Reading and Writing Application Data 363 Design Considerations .363
Reading and Writing User Defaults .366
Understanding the iPhone File System Sandbox .381
Implementing File System Storage .384
Further Exploration .404
Summary .405
Q&A .405
Workshop .406
Trang 9HOUR 15: Building Rotatable and Resizable User Interfaces 407
Rotatable and Resizable Interfaces .407
Creating Rotatable and Resizable Interfaces with Interface Builder .411
Reframing Controls on Rotation .416
Swapping Views on Rotation .423
Further Exploration .429
Summary .430
Q&A .430
Workshop .431
HOUR 16:Using Advanced Touches and Gestures 433 Multitouch Gesture Recognition .434
Using Gesture Recognizers .435
Further Exploration .448
Summary .449
Q&A .449
Workshop .449
HOUR 17:Sensing Orientation and Motion 451 Understanding iPhone Motion Hardware .451
Accessing Orientation and Motion Data .454
Sensing Orientation .458
Detecting Tilt and Rotation .462
Further Exploration .471
Summary .472
Workshop .473
HOUR 18:Working with Rich Media 475 Exploring Rich Media .475
Preparing the Media Playground Application .478
Using the Movie Player .482
Creating and Playing Audio Recordings .486
Using the Photo Library and Camera .492
Trang 10Accessing and Playing the iPod Library .495
Further Exploration .501
Summary .502
Q&A .502
Workshop .503
HOUR 19: Interacting with Other Applications 505 Extending Application Integration .505
Using Address Book, Email, and Maps… Oh My! .509
Further Exploration .526
Summary .527
Q&A .527
Workshop .527
HOUR 20: Implementing Location Services 529 Understanding Core Location .529
Creating a Location-Aware Application .534
Understanding the Magnetic Compass .541
Further Exploration .549
Summary .550
Q&A .550
Workshop .551
HOUR 21: Building Background-Aware Applications 553 Understanding iOS 4 Backgrounding .554
Disabling Backgrounding .558
Handling Background Suspension .559
Implementing Local Notifications .561
Using Task-Specific Background Processing .564
Completing a Long-Running Background Task .570
Further Exploration .576
Summary .577
Q&A .577
Workshop .577
Trang 11Understanding the Universal Window-Based Application Template .581
Other Universal Application Tools .596
Further Exploration .598
Summary .599
Q&A .599
Workshop .599
HOUR 23:Application Debugging and Optimization 601 Debugging in Xcode .601
Monitoring with Instruments .614
Profiling with Shark .620
Further Exploration .627
Summary .627
Q&A .627
Workshop .628
HOUR 24:Distributing Applications Through the App Store 629 Preparing an Application for the App Store .630
Submitting an Application for Approval .642
Promoting Your Application .649
Exploring Other Distribution Methods .655
Summary .657
Q&A .657
Workshop .657
Trang 12John Ray is currently serving as a Senior Business Analyst and Development Team
Manager for the Ohio State University Research Foundation He has written numerous
books for Macmillan/Sams/Que, including Using TCP/IP: Special Edition, Teach Yourself
Dreamweaver MX in 21 Days, Mac OS X Unleashed, and Teach Yourself iPad Development in 24 Hours As a Macintosh user since 1984, he strives to ensure that each project presents the
Macintosh with the equality and depth it deserves Even technical titles such as Using TCP/IP
contain extensive information about the Macintosh and its applications and have garnerednumerous positive reviews for their straightforward approach and accessibility to beginnerand intermediate users
You can visit his website at http://teachyourselfiphone.com or follow him on Twitter at
#iPhoneIn24
Dedication
This book is dedicated to everyone who makes me smile, even if only on occasion.
Thanks for keeping me stay sane during long nights of typing.
Acknowledgments
Thank you to the group at Sams Publishing—Laura Norman, Sandra Schroeder, Keith Cline,Matthew David—for providing amazing support during the creation of this book Your thor-oughness and attention to detail make the difference between a book that works and onethat bewilders
Thanks to my friends, family, and pets Deepest apologies to my fish tank I swear I’ll getyou working right soon
Trang 13As the reader of this book, you are our most important critic and commentator We value
your opinion and want to know what we’re doing right, what we could do better, whatareas you’d like to see us publish in, and any other words of wisdom you’re willing to passour way
You can email or write me directly to let me know what you did or didn’t like about thisbook—as well as what we can do to make our books stronger
Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message.
When you write, please be sure to include this book’s title and author as well as your nameand phone or email address I will carefully review your comments and share them with theauthor and editors who worked on the book
E-mail: feedback@quepublishing.com
Associate PublisherSams Publishing
800 East 96th StreetIndianapolis, IN 46240 USA
Reader Services
Visit our website and register this book at informit.com/register for convenient access to anyupdates, downloads, or errata that might be available for this book
Trang 14Over the past four years, Apple has changed the way we think about mobile computing.The iOS Platform has changed the way that we, the public, think about our mobile comput-ing devices With full-featured applications and an interface architecture that demonstratesthat small screens can be effective workspaces, the iPhone has become the smartphone ofchoice for users and developers alike.
Part of what makes the iPhone such a success is the combination of an amazing interfaceand an effective software distribution method With Apple, the user experience is key TheiOS is designed to be controlled with your fingers rather by using a stylus or keypad Theapplications are “natural” and fun to use, instead of looking and behaving like a clumsyport of a desktop app Everything from interface to application performance and battery lifehas been considered The same cannot be said for the competition
Through the App Store, Apple has created the ultimate digital distribution system for opers Programmers of any age or affiliation can submit their applications to the App Storefor just the cost of a modest yearly Developer Membership fee Games, utilities, and full-fea-ture applications have been built for everything from pre-K education to retirement living
devel-No matter what the content, with a user base as large as the iPhone, an audience exists
In 2010, Apple introduced the iPad and iPhone 4 platforms—bringing larger, faster, andhigher-resolution capabilities to the iOS Although these devices will only be a few months
“old” by the time you read this, they will already be in the hands of millions of users,eagerly awaiting the next great app
My hope is that this book will bring iOS development to a new generation of developers
Teach Yourself iPhone Development in 24 Hours provides a clear natural progression of skills
development, from installing developer tools and registering with Apple, to submitting anapplication to the App Store It’s everything you need to get started in 24 one-hour lessons
Who Can Become an iPhone Developer?
If you have an interest in learning, time to invest in exploring and practicing with Apple’sdeveloper tools, and an Intel Macintosh computer running Snow Leopard, you have every-thing you need to begin developing for the iPhone
Developing an application for the iPhone won’t happen overnight, but with dedication andpractice, you can be writing your first applications in a matter of days The more time youspend working with the Apple developer tools, the more opportunities you’ll discover for
Trang 15You should approach iPhone application development as creating software that you want to
use, not what you think others want If you’re solely interested in getting rich quick, you’relikely to be disappointed (The App Store is a crowded marketplace—albeit one with a lot ofroom—and competition for top sales is fierce.) However, if you focus on building apps thatare useful and unique, you’re much more likely to find an appreciative audience
Who Should Use This Book?
This book targets individuals who are new to development for the iPhone and have ence using the Macintosh platform No previous experience with Objective-C, Cocoa, or theApple developer tools is required Of course, if you do have development experience, some
experi-of the tools and techniques may be easier to master, but the authors do not assume thatyou’ve coded before
That said, some things are expected of you, the reader Specifically, you must be willing toinvest in the learning process If you just read each hour’s lesson without working through thetutorials, you will likely miss some fundamental concepts In addition, you need to spend timereading the Apple developer documentation and researching the topics presented in this book.There is a vast amount of information on iPhone development available, and only limitedspace in this book This book covers what you need to forge your own path forward
What Is (and Isn’t) in This Book?
The material in this book specifically targets iOS release 4 Much of what you’ll be learning
is common to all the iOS releases, but this book also covers several important advances in
4, such as Gestures, embedded video playback, multitasking, universal (iPhone/iPad) cations, and more!
appli-Unfortunately, this is not a complete reference for the iPhone APIs; some topics just requiremuch more space than this book allows Thankfully, the Apple developer documentation isavailable directly within the free tools you’ll be downloading in Hour 1, “Preparing YourSystem and iPhone for Development.” In many hours, you’ll find a section titled “FurtherExploration.” This will identify additional related topics of interest Again, a willingness toexplore is an important quality in becoming a successful iPhone developer!
Each coding lesson is accompanied by project files that include everything you need to pile and test an example or, preferably, follow along and build the application yourself Besure to download the project files from the book’s website at http://teachyourselfiphone.com
com-In addition to the support website, you can follow along on Twitter! Search for #iPhonecom-In24
on Twitter to receive official updates and tweets from other readers Use the hashtag
#iPhoneIn24 in your tweets to join the conversation To send me messages via Twitter, begineach tweet with @johnemeryray
Trang 16Preparing Your System and
iPhone for Development
What You’ll Learn in This Hour:
What makes an iPhone an iPhone
Where to get the tools you need to develop for the iPhone
How to join the iOS Developer Program
The need for (and use of) provisioning profiles
What to expect during the first few hours of this book
The iPhone opens up a whole realm of possibilities for developers—a multitouch interface,always-on Internet access, video, and a whole range of built-in sensors can be used to cre-ate everything from games to serious productivity applications Believe it or not, as a newdeveloper, you have an advantage You will be starting fresh, free from any preconceivednotions of what is possible in a handheld application Your next big idea may wellbecome the next big thing on Apple’s App Store
This hour will get you prepared for iPhone development You’re about to embark on theroad to becoming an iPhone developer, but ‘you need to do a bit of prep work before youstart coding
Welcome to the iOS Platform
If you’re reading this book, you probably already have an iPhone, and that means youalready understand how to interact with its interface Crisp graphics, amazing responsive-ness, multitouch, and hundreds of thousands of apps—this just begins to scratch the sur-face As a developer, however, you’ll need to get accustomed to dealing with a platformthat, to borrow a phrase from Apple, forces you to “think different.”
Trang 17Display and Graphics
The iPhone screen is 320×480 points—giving you a limited amount of space to ent your application’s content and interface (see Figure 1.1) Notice that I said
pres-“points”, and not pixels! Prior to the release of the iPhone 4’s Retina display, the
iPhone was 320×480 pixels Now, the actual resolution of an iOS device is abstractedbehind a scaling factor This means that while you will be working the numbers
320×480 for positioning elements, you may have more pixels than that The iPhone
4, for example, has a scaling factor of 2, which means that it is really a(320×2)×(480×2) or 640×960 resolution device Although that might seem like quite
a bit of screen real estate, remember that all these pixels are displayed in a screenthat is roughly 3.5-inch” diagonal
Know? We’ll look more at how scaling factors work when we position objects on thescreen throughout the book The important thing to know is that when you’re
build-ing your applications, the iOS will automatically take the scalbuild-ing factor into play todisplay your apps and their interfaces at the highest possible resolution with
rarely any additional work on your part!
Although this might seem limiting, consider that desktop computers only recentlyexceeded this size, and many websites are still designed for 800×600 In addition,
Trang 18By the
Way
the iPhone’s display is dedicated to the currently running application You will have
one window to work in You can change the content within that window, but the
desktop and multiwindow application metaphors are gone
The screen limits aren’t a bad thing As you’ll learn, the iPhone development tools
give you plenty of opportunities to create applications with just as much depth as
your desktop software—albeit with a more structured and efficient interface design
The graphics that you display on your screen can include complex animated 2D
and 3D displays thanks to the OpenGL ES implementation available on all iPhone
models OpenGL is an industry standard for defining and manipulating graphic
images that is widely used when creating games The iPhone 3GS and 4 improve
these capabilities with an updated 3D chipset and more advanced version of
OpenGL (ES 2.0), but all the models have very respectable imaging abilities
Application Resource Constraints
As with the HD displays on our desktops and laptops, we’ve grown accustomed to
processors that can work faster than we can click The iPhone uses a ~400MHz ARM
in the early models, a ~600MHz version in the 3GS, and a 1GHz A4 in the iPhone 4
The A4 is a “system on a chip” that provides CPU, GPU, and other capabilities to the
device and is the first Apple-designed CPU to be used in quite a while
Apple has gone to great lengths to keep the iPhone responsive regardless of what
you’re doing Unfortunately, that means that unlike the Mac OS, your iPhone’s
capability to multitask is limited In iOS 4, Apple has created a limited set of
multi-tasking APIs for very specific situations These enable you to perform some tasks in
the background, but your application can never assume that it will remain running
The iOS preserves the user experience beyond above all else
Another constraint that you need to be mindful of is the available memory In the
original and iPhone 3G devices, 128MB of RAM is available for the entire system,
including your application There is no virtual memory, so you must carefully manage
the objects that your application creates In the iPhone 3GS Apple upped the ante to
256MB and, with the iPhone 4, Apple has graciously provided 512MB! This is great
for us, but keep in mind that there are no RAM upgrades for earlier models!
Throughout the book, you’ll see reminders to “release” memory when you’re done
using it Even though you might get tired of seeing it, this is a very important
process to get used to
Trang 19The iPhone has the ability to always be connected to the Internet via a cellularprovider (such as AT&T in the United States) This wide-area access is supplementedwith built-in WiFi and Bluetooth in all iPhone models WiFi can provide desktop-likebrowsing speeds within the range of a wireless hot spot Bluetooth, on the otherhand, can be used to connect a variety of peripheral devices to your iPhone, includ-ing a keyboard!
As a developer, you can make use of the Internet connectivity to update the content
in your application, display web pages, and create multiplayer games The onlydrawback is that applications that rely heavily on 3G data usage stand a greaterchance of being rejected from the App Store These restrictions have been lessened inrecent months, but it is still a point of frustration for developers
Input and Feedback
The iPhone shines when it comes to input and feedback mechanisms and your ability
to work with them You can read the input values from the capacitive multitouch(five-finger!) screen, sense motion and tilt via the accelerometer and gyroscope (iPhone4), determine where you are using the GPS (3G/3GS), see which way you’re facing withthe digital compass (3GS and iPhone 4), and understand how the phone is being usedwith the proximity and light sensors The phone itself can provide so much data toyour application about how and where it is being used that the device itself trulybecomes a controller of sorts—much like (but surpassing!) the Nintendo Wii
The iPhone also supports capturing pictures and video (3GS and iPhone 4) directlyinto your applications, opening a realm of possibilities for interacting with the realworld Already applications are available that identify objects you’ve taken pictures
of and that find references to them online (such as the Amazon Mobile app).Finally, for each action your user takes when interacting with your application, youcan provide feedback This, obviously, can be visible feedback on the screen, or itcan be high-quality audio and force feedback via vibration As a developer, you canleverage all these capabilities (as you’ll learn in this book)
That wraps up our quick tour of the iOS platform Never before has a single devicedefined and provided so many capabilities for a developer As long as you thinkthrough the resource limitations and plan accordingly, a wealth of developmentopportunities awaits you
Trang 20Did you
Know?
Although this book targets the iPhone specifically, nearly all the information
car-ries over to development for the iPod Touch and iPad These systems differ in
capabilities, such as support for a camera and GPS, but the development
tech-niques are otherwise identical
Becoming an iOS Developer
Being an iPhone developer requires more than just sitting down and writing a
pro-gram You need a modern Intel Macintosh desktop or laptop running Snow Leopard
and at least 6GB of free space on your hard drive The more screen space you have
on your development system, the easier it will be to switch between the coding,
design, simulation, and reference tools that you’ll need to be using That said, I’ve
worked perfectly happily on a 13-inch MacBook Pro, so an ultra-HD multimonitor
setup certainly isn’t necessary
So assuming you already have a Mac, what else do you need? The good news is that
there isn’t much more, and it won’t cost you a cent to write your first application.
Joining the Apple Developer Program
Despite somewhat confusing messages on the Apple website, there really is no fee
associated with joining the Apple Developer Program, downloading the iOS SDK
(Software Development Kit), writing iPhone applications, and running them on
Apple’s iPhone Simulator
Limitations do apply, however, to what you can do for free If you want to have
early access to beta versions of the iOS and SDK, you must be a paid member If you
want to load the applications you write on a physical iPhone device or distribute
them via the App Store, you’ll also need to pay the membership fee Most
applica-tions in this book will work just fine on the simulator provided with the free tools, so
the decision on how to proceed is up to you
Perhaps you aren’t yet sure whether the paid program is right for you Don’t worry;
you can upgrade at any time I recommend starting out with the free program and
upgrading after you’ve had a chance to write a few sample applications and to run
them in the simulator
Obviously, things such as motion sensor input and GPS readings can’t be
accu-rately presented in the simulator, but these are special cases and aren’t needed
until later in this book
Did you
Know?
Trang 21By the
Way
If you don’t yet have an Apple ID, click the Register link, and then click Get Started
on the subsequent page When the registration starts, choose Create an Apple ID inthe first step, as shown in Figure 1.3
If you choose to pay, the paid Developer Program offers two levels: a standard gram ($99) for those who will be creating applications that they want to distributefrom the App Store, and an enterprise program ($299) for large (500+ employee)
pro-companies that want to develop and distribute applications in-house but not
through the App Store Chances are, the standard program is what you want
The standard ($99) program is available for both companies and individuals In caseyou want to publish to the App Store with a business name, you’ll be given the option
of choosing a standard “individual” or “company” program during the registration
Registering as a Developer
Big or small, free or paid, your venture into iPhone development begins on Apple’swebsite To start, visit the Apple iPhone Dev Center (http://developer.apple.com/iphone), shown in Figure 1.2
If you already have an Apple ID from using iTunes or other Apple services, lations, you’re almost done! Use the Log In button to access your account, agree toApple’s developer terms, and provide a few pieces of additional information for yourdeveloper profile You’ll immediately be granted access to the free developer resources!
Trang 22FIGURE 1.3
You’ll use anApple ID toaccess all thedeveloperresources
The registration process walks you through the process of creating a new Apple ID
and collects information about your development interests and experience, as
shown in Figure 1.4
Upon completion of the registration, Apple verifies your email address by sending
you a clickable link to activate your account
FIGURE 1.4
The multistepregistrationprocess collects
a variety ofinformationabout yourdevelopmentexperience
Trang 23Joining a Paid Developer Program
After you have a registered and activated Apple ID, you can decide to join a paid gram or to continue using the free resources If you choose to join a paid program,again point your browser to the iPhone Dev Center (http://developer.apple.com/iphone)and click the Register link Choose Use an Existing Apple ID for the Developer Programoption, shown in Figure 1.3
pro-On the page that appears, look for the Join Today link and click it The registrationtool will now guide you through applying for the paid programs, including choosingbetween the standard and company options, as shown in Figure 1.5
to the iPhone Dev Center and clicking the Check Your Enrollment Status Now link.Click the Register link to create a new free Developer Membership, or follow thelinks in the iOS Developer Program section (currently http://developer.apple.com/iphone/program) to join a paid program
Installing the iOS Developer Tools
After you’ve registered your Apple ID, you can immediately download the currentrelease version of the iOS developer tools directly from the iPhone Dev Center
Trang 24Did you
Know?
(http://developer.apple.com/iphone) Just click the Download link and sit back while
your Mac downloads the massive (~2.5GB) SDK disk image
If you have the free Developer Membership, you’ll likely see just a single SDK to
download (the current release version of the development tools) If you’ve become
a paid program member, you may see additional links for different versions of the
SDK (3.2, 4.0, and so on) The examples in this book are based on the 4.0+
series of SDKs, so be sure to choose that option if presented
When the download completes, open the resulting disk image, and double-click the
Xcode and iPhone SDK for Snow Leopard icon Doing so launches the Mac OS X
Installer application, which will assist you in the installation You don’t have to
change any of the defaults for the installer, so just read and agree to the software
license and click Continue to proceed through the steps
Unlike most applications, the Apple developer tools are installed in a folder called
Developer located at the root of your hard drive Inside the Developer folder are
dozens of files and folders containing developer frameworks, source code files,
exam-ples, and of course, the developer applications themselves Nearly all your work in
this book will start with the application Xcode, located in the Developer/Applications
folder (see Figure 1.6)
FIGURE 1.6
Most of yourwork with thedeveloper toolswill start in theDeveloper/Applicationsfolder
Although we won’t get into real development for a few more hours, we will be
con-figuring a few options in Xcode in the next section, so don’t forget where it is!
Trang 25Creating a Development Provisioning Profile
Even after you’ve obtained an Apple Developer Membership, joined a paidDeveloper Program, and downloaded and installed the iOS development tools, youstill won’t be able to run on your iPhone any applications that you write! Why?Because you haven’t created a development provisioning profile yet
In many development guides, this step isn’t covered until after development begins
In my mind, once you’ve written an application, you’re going to want to ately run it on the iPhone Why? Because it’s just cool to see your own code running
immedi-on your own device!
What’s a Development Provisioning Profile?
Like it or not, Apple’s current approach to iOS development is to make absolutelycertain that the development process is controlled—and that groups can’t just dis-tribute software to anyone they want The result is a rather confusing process thatties together information about you, any development team members, and yourapplication into a “provisioning profile.”
A development provisioning profile identifies the developer who may install anapplication, an ID for the application being developed, and the “unique device
identifiers” for each iPhone that will run the application This is only for the
develop-ment process When you are ready to distribute an application via the App Store or
to a group of testers (or friends!) via ad hoc means, you’ll need to create a separate
“distribution” profile Because we’re just starting out, this isn’t something you needright away We talk more about distribution profiles in Hour 24, “DistributingApplications Through the App Store.”
Generating and Installing a Development Provisioning Profile
Creating a provisioning profile can be frustrating and seem outrageously convoluted.Apple has streamlined the process tremendously with an online DevelopmentProvisioning Assistant, but we still have to jump through some hoops Let’s bite thebullet and get through this!
Getting Your iPhone Unique Device Identifier
To run your application on a real iPhone, you need the ID that uniquely identifiesyour iPhone from the thousands of other iPhones To find this, first make sure thatyour device is connected to your computer, and then launch Xcode from the
Trang 26Developer/Applications folder When Xcode first launches, immediately choose
Window, Organizer from the menu The Organizer utility slightly resembles iTunes
in its layout You should see your iPhone listed in the far-left column of the
Organizer under the Devices section Click the icon to select it, and then click the
Use for Development button Your screen should now resemble Figure 1.7
FIGURE 1.7
First, grab the
ID of youriPhone
The Identifier field is the unique device ID that we’re looking for Go ahead and copy
it to the Clipboard You’ll need to paste it into the Provisioning Assistant shortly
Starting the Provisioning Assistant
Next, head to the Apple website and the iOS Dev Center (http://developer.apple
com/ios) Make sure that you’ve logged in to the site, and then click the
Provisioning Portal link, currently located in the upper-right side of the page The
Provisioning Portal is designed to give you access to the tools you need to create
pro-visioning and distribution profiles It also includes the Development Propro-visioning
Assistant, which is the web utility that will make our lives much easier Click the
Launch Assistant button (see Figure 1.8)
The assistant will launch in your web browser and display a short splash screen
Click the Continue button to begin
Trang 27multiple applications, however, they can share keychain data.
For the purposes of this book, there’s no reason the tutorial apps can’t share a singleApp ID, so create a new ID named anything you want If you have already createdApp IDs in the past, you’ll be given the option to choose an existing ID I’m creating
a new App ID, Tutorials, as shown in Figure 1.9 Enter the ID and click Continue tomove on
Assigning a Development Device
Next you are asked to assign a development device, as shown in Figure 1.10 Thisdevice ID identifies which iPhone will be allowed to run the applications you create.Enter a meaningful description for the device (“Johns iPhone,” for example), andthen paste the string you copied from the Xcode organizer into the Device ID field.Click Continue to move on
Trang 28Note that as with the App IDs, if you’ve already used a device ID in the past, you
will be given the option of simply selecting it from a drop-down list
FIGURE 1.9
An App ID can
be used for asingle applica-tion or group of
applications.
FIGURE 1.10
Assign a devicethat can runyour application
Trang 29Generating a Certificate Signing Request
Now things are getting fun The next step takes place outside of your browser.Leaving the Development Provisioning Assistant open, go to the Applications/Utilitiesfolder on your hard drive and open the Keychain Access utility Choose KeychainAccess, Certificate Assistant, Request a Certificate from a Certificate Authority fromthe menu (see Figure 1.11)
Trang 30Uploading the Certificate Signing Request
Return to the Development Provisioning Assistant in your web browser Click
Continue until you are prompted to submit the certificate signing request that you
just generated (see Figure 1.13) Click the Choose File button so that you can select
the request file, and then click Continue to upload it
FIGURE 1.13
Upload the tificate signingrequest toApple
cer-Naming and Generating the Provisioning Profile
We’re almost done! After uploading the request, you’ll be prompted to name the
provisioning profile (see Figure 1.14) Because this profile contains information that
can potentially identify individual phones and applications, you should choose
something relevant to how you intend to use it In this case, I’m only interested in
using it as a generic development profile for all of my apps, so I’m naming it iPhone
Development Profile Not very creative, but it works
Click the Generate button to create your provisioning profile This may take 20 to 60
seconds, so be patient The screen will eventually refresh to show the final profile
information, as shown in Figure 1.15
Our final steps will be downloading and installing the profile, and downloading and
installing a security certificate that will be associated with the profile
Trang 31Downloading the Development Provisioning Profile and Certificate
At this point, your profile has been generated, along with a security certificate that can beused to uniquely associate your applications with that profile All that remains is down-loading and installing them Click the Continue button to access the provisioning profiledownload screen, as shown in Figure 1.16 Click the Download Now button to save theprofile to your Downloads folder (file extension mobileprovision)
Trang 32As much as I hate to say it, the next thing to do is to ignore the onscreen instructions—
the installation process that Apple describes in the assistant isn’t the most efficient
route Instead, click the Continue button until you are given the option of downloading
the development certificate, as shown in Figure 1.17
Click the Download button to download the certificate file (file extension cer) to
your Downloads folder You are now finished with the Provisioning Assistant and
can safely exit
FIGURE 1.16
Download theprovisioning profile
FIGURE 1.17
Download thedevelopmentcertificate
Trang 33Installing the Development Provisioning Profile and Certificate
To install the profile and certificate, we just need to exercise our double-click skills.First, install the development certificate by double-clicking it Doing so opens KeychainAccess and prompts you for the keychain where the certificate should be installed.Choose the login keychain, and then click Add, as demonstrated in Figure 1.18
Trang 34Did you
Know?
After you have a development machine configured, you can easily configure other
computers using the Developer Profile item in the Xcode organizer The Export
Developer Profile and Import Developer Profile buttons will export (and
subse-quently import) all your developer profiles/certificates in a single package
But Wait… I Have More Than One iOS Device!
The Development Provisioning Assistant helps you create a provisioning profile for
a single iPhone, iPad, or iPod Touch device But what if you have multiple devices
that you want to install onto? No problem You’ll need to head back to the
Provisioning Portal and click the Devices link on the left side of the page From
there, you can add additional devices that will be available to your profile
Next, click the Provisioning link, also on the left side of the page, and use the Edit
link to modify your existing profile to include another iPhone, as demonstrated in
Figure 1.20
Finally, you’ll need to click the Download link to redownload the modified profile
and then import it into Xcode so that the additional device is available
FIGURE 1.20
Add additionaldevices to aprovisioning pro-file within theweb portal.Remember toredownload theprofile andinstall it!
Testing the Profile with an iPhone App
It seems wrong to go through all of that work without some payoff, right? For a
real-world test of your efforts, let’s actually try to run an application on your iPhone If
you haven’t downloaded the project files to your computer, now is a good time to
visit http://teachyourselfiphone.com and download the archives
Trang 35By the
Way
Within the Hour 1 Projects folder, open the Welcome folder Double-clickWelcome.xcodeproj to open a simple application in Xcode After the project opens,your display should be similar to Figure 1.21
Xcode will install the correct provisioning profile on your device, and, after a fewseconds, the application should be installed and launched on your iPhone, as seen
in Figure 1.22
You can now exit Xcode and quit the Welcome application on your iPhone
When you clicked Build and Run, the Welcome application was installed and
start-ed on your iPhone It will remain there until you remove it manually Just touch andhold the Welcome icon until it starts wiggling, and then delete the application asyou would any other Applications installed with your development certificate willstop working when the certificate expires (120 days after it was issued)
Trang 36Developer Technology Overview
Over the course of the next few hours, you will be introduced to the technologies
that you’ll be using to create iPhone applications The goal is to get you up to speed
on the tools and technology, and then you can start actively developing This means
you’re still a few hours away from writing your first app, but when you start coding,
you’ll have the necessary background skills and knowledge to successfully create a
wide variety of applications
The Apple Developer Suite
In this hour, you downloaded and worked with the Xcode application This is just
one piece (albeit an important piece) of the developer suite that you will be using
throughout this book Xcode, coupled with Interface Builder and the iPhone
Simulator, will make up your development environment These three applications
are so critical, in fact, that two hours (2 and 4) are devoted to covering them
It’s worth mentioning that almost every iPhone, iPad, iPod, and Macintosh
applica-tion you run, whether created by a single developer at home or a huge company, is
built using the Apple developer tools This means that you have everything you
need to create software as powerful as any you’ve ever run
Later in the book, you’ll be introduced to additional tools in the suite that can help
you debug and optimize your application
FIGURE 1.22
Congratulations,you’ve justinstalled yourfirst home-grown iPhoneapplication!
Trang 37By the
Way During the writing of this book, Apple released a “developer preview” of Xcode 4.
Because there is no known release schedule for Xcode 4, and you can’t yet use it
to build real applications, we are writing with the tried-and-true Xcode 3.2 Forthose who want to make the transition, we’ll be providing an online introduction toXcode 4 (as soon as it is publicly available) at the book’s support site:
http://teachyourselfiphone.com/ Be sure to check it out!
Objective-C
Objective-C is the language that you’ll be using to write your applications It vides the structure for our applications and is to control the logic and decision mak-ing that goes on when an application is running
pro-If you’ve never worked with a programming language before, don’t worry Hour 3,
“Discovering Objective-C: The Language of Apple Platforms,” covers everything youneed to get started Developing for the iPhone in Objective-C is a unique programmingexperience, even if you’ve used other programming languages in the past The lan-guage is unobtrusive and structured in a way that makes it easy to follow After yourfirst few projects, Objective-C will fade into the background, letting you concentrate onthe specifics of your application
Cocoa Touch
While Objective-C defines the structure for iPhone applications, Cocoa Touch defines
the functional building blocks, called classes, that can make the iPhone do certain
things Cocoa Touch isn’t a “thing,” per se, but a collection of interface elements, datastorage elements, and other handy tools that you can access from your applications
As you’ll learn in Hour 4, “Inside Cocoa Touch,” you can access literally hundreds ofdifferent Cocoa Touch classes and do thousands of things with them This book cov-ers quite a few of the most useful classes and gives you the pointers you need toexplore even more on your own
Model-View-Controller
The iOS platform and Macintosh use a development approach called Controller (MVC) to structure applications Understanding why MVC is used and thebenefits it provides will help you make good decisions in structuring your most com-plex applications Despite the potentially complicated-sounding name, MVC is real-
Model-View-ly just a way to keep your application projects arranged so that you can easiModel-View-lyupdate and extend them in the future You’ll take a more detailed look at MVC inHour 6, “Model-View-Controller Application Design.”
Trang 38This hour introduced you to the iOS platform, its capabilities, and its limitations
You learned about the iPhone’s graphic features, RAM size, and the various sensors
that you can use in your applications to create uniquely “aware” experiences We
also discussed the Apple iPhone developer tools, how to download and install them,
and the differences between the varying pay-for developer programs To prepare you
for actual on-phone development, you explored the process of creating and
installing a Development Provisioning Profile in Xcode and even installed an
appli-cation on your phone
The hour wrapped up with a quick discussion of the development technologies that
make up the first part of the book and form the basis for all the iPhone
develop-ment you’ll be doing
Q&A
Q I thought the iPhone had at minimum 16GB of RAM in the low-end model
and 32GB on the high-end model Doesn’t it?
A The “memory” capabilities for the iPhone that are advertised to the public are
the storage sizes available for applications, songs, and so forth It is separate
from the RAM that can be used for executing programs If Apple implements
virtual memory in a future version of iOS, it is possible that the larger storage
could be used for increasing available RAM
Q What platform should I target for development?
A That depends on your goals If you want to reach the largest audience, consider
a universal application that works on the iPhone, iPad, and iPod Touch We
examine this development possibility later in Hour 22, “Building Universal
Applications.” If you want to make use of the most capable hardware, you can
certainly target the unique capabilities of the iPhone 4, but you will potentially
be limiting the size of your customer base
Q Why isn’t the iPhone (and iOS platform) open?
A Great question Apple has long sought to control the user experience so that it
remains “positive” regardless of how users have set up their device, be it a
Mac, an iPhone, or an iPhone By ensuring that applications can be tied to a
developer and enforcing an approval process, Apple attempts to limit the
potential for a harmful application to cause damage to data or otherwise
neg-atively impact the user Whether this is an appropriate approach, however, is
open to debate
Trang 39Workshop Quiz
1 What is the resolution of the iPhone screen?
2 What is the cost of joining an individual iOS Developer Program?
3 What language will you use when creating iPhone applications?
Answers
1 Trick question The iPhone screen has 320×480 points, but you can’t tell howmany pixels unless you multiply by the scaling factor The iPhone 4 has ascaling factor of 2; all other models have a scaling factor of 1
2 The Developer Program costs $99 a year for the individual option
3 Objective-C will be used for iPhone development
Activities
1 Establish an Apple Developer Membership and download and install the oper tools This is an important activity that, if you didn’t follow along in thecourse of the hour, should be completed before starting the next hour’s lesson
devel-2 Review the resources available in the iOS Dev Center Apple has publishedseveral introductory videos and tutorials that supplement what you’ll learn inthis book
Trang 40Introduction to Xcode and the iPhone Simulator
What You’ll Learn in This Hour:
How to create new projects in Xcode
Code editing and navigation features
Where to add classes and resources to a project
How to modify project properties
Compiling for the iPhone and the iPhone Simulator
How to interpret error messages
Features and limitations of the iPhone Simulator
The core of your work in the Apple Developer Suite will be spent in three applications:Xcode, Interface Builder, and the iPhone Simulator This trio of apps provides all the toolsthat you need to design, program, and test applications for the iPhone And, unlike otherplatforms, the Apple Developer Suite is entirely free!
This hour walks you through the basics you need to work within two of the three components—Xcode and the iPhone Simulator—and you’ll get some hands-on practice working with each
We cover the third piece, Interface Builder, in Hour 5, “Exploring Interface Builder.”
Using Xcode
When you think of coding—actually typing the statements that will make your iPhone meetApple’s “magical” mantra—think Xcode Xcode is the IDE, or integrated development envi-ronment, that manages your application’s resources and lets you edit the code that ties thedifferent pieces together