Xcode 4 Cookbook free download ebook

  Xcode 4 Cookbook

Over 100 recipes to build your own fun and exciting

iOS applications Steven F. Daniel BIRMINGHAM - MUMBAI

  Xcode 4 Cookbook Copyright © 2013 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system,

or transmitted in any form or by any means, without the prior written permission of the

publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the

information presented. However, the information contained in this book is sold without

warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

  First published: May 2013 Production Reference: 1160513 Published by Packt Publishing Ltd. Livery Place

35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-84969-334-9

  www.packtpub.com

  Cover Image by Evelyn lam ( )

  yeeyean@gmail.com

  

Credits

  Author Steven F. Daniel

  Reviewers Bob Sander-Cederlof Dave Hersey Jean-Yves Mengant Robert Wohnoutka

  Acquisition Editor Mary Nadar

  Lead Technical Editor Dayan Hyames

  Project Coordinator Amey Sawant

  Proofreader Amy Guest

  Technical Editors Kaustubh Mayekar Ankita Meshram Veena Pagare Akshata Patil Zafeer Rais

  Indexer Monica Ajmera Mehta

  Graphics Ronak Dhruv

  Production Coordinator Manu Joseph

  Cover Work Manu Joseph About the Author is originally from London, England, but lives in Australia.

  Steven F. Daniel He is the owner and founder of GENIESOFT STUDIOS ( http://www.geniesoftstudios.

  ), a software development company based in Melbourne, Victoria, that currently

  com/ develops games and business applications for the iOS, Android, and Windows platforms.

  Steven is an experienced software developer with more than 13 years of experience developing desktop and web-based applications for a number of companies including, insurance, banking and finance, oil and gas, and local and state government. Steven is always interested in emerging technologies, and is a member of the SQL Server Special Interest Group (SQLSIG) and the Java Community. He has been the co-founder and Chief Technology Officer (CTO) of SoftMpire Pty Ltd., a company that focused primarily on developing business applications for the iOS and Android platforms.

  He is the author of Xcode 4 iOS Development Beginner's Guide, iOS 5 Essentials, and iPad Enterprise Application Development Blueprints. Y , or follow him

   Acknowledgement No book is the product of just the author—he just happens to be the one with his name on the cover. A number of people contributed to the success of this book, and it would take more space if I have to thank each one individually. A special shout-out goes to Mary Nadar, my acquisition editor, who is the reason that this book exists. Thank you Mary for believing in me and for being a wonderful guide throughout this whole process. I would like to thank Amey Sawant for ensuring that I stayed on track and got my chapters in on time, and to Dayan Hyames for his brilliant suggestive approach with the chapter rewrites. I would also like to extend my thanks to each of my Technical Editors for their brilliant suggestions and improvements to each chapter, as well as ensuring that we met our timeframes, and delivery for this book. It has been a great privilege to work with each of you on this book. Lastly, to my reviewers, thank you so much for your valued suggestions and improvements, making this book what it is. I am grateful to each and every one of you. Thank you also to the entire Packt Publishing team for working so diligently to help bring out a high quality product. Finally, a big thank you to the engineers at Apple for creating the iPhone and the iPad, and providing developers with the tools to create fun and sophisticated applications. You guys rock. Finally, I'd like to thank all of my friends for their support, understanding, and encouragement during the writing process. It is a privilege to know each and every one of you.

About the Reviewers has been programming for over 55 years, including 21 years at

  Bob Sander-Cederlof

Adobe Systems. During the Apple II era, as owner of S-C Software Corporation, Bob published

the Apple Assembly Line newsletter for over eight years, along with software such as the S-C Macro Assembler. Other interests include Christianity, the Bible, and genealogy. More at .

  http://www.txbobsc.com

  

Dave Hersey has over 35 years of experience in Apple software development, dating back

to the Apple II personal computer in 1977. In 2000, after over 6 years in software engineering

at Apple Computer, Dave started Paracoders Inc. focusing on custom Mac OS X-based application and driver development. In 2008, Dave's company expanded into iOS (iPhone) mobile applications, followed by Android applications soon after. Some big-named clients

including Paramount Home Entertainment, Lionsgate Entertainment, Seagate, Creative Labs,

Monterey Bay Aquarium, and Kraft Foods. Most recently, Dave's business has expanded to

include additional mobile and server-side platforms as well as support services. As a result,

the custom software development division of Paracoders now operates as "Torchlight Apps"

( ).

  

  

Dave was also a technical reviewer for Creating Games with cocos2d for iPhone 2 and HTML5

Game Development with GameMaker. When he's not learning new technologies, developing

software, or reviewing books, Dave stays busy with his wife raising three children, three dogs, two parakeets, and about 22 ducks at last count. is the CTO at SEFAS Innovation, a French software editor. He lives in Jean-Yves Mengant France in the Paris area.

  

Jean-Yves has been in the IT industry for more than 30 years, working on many technologies and

languages from Mainframes MVS to Unixes Mac IOS and Android in Assembly Java, C++, and Objective-C. He has written articles for Linux Journal, C++ users Journal, and Dr Dobbs journal.

  

I would like to thank my beloved wife Martine, for supporting my work during

all those years, and and my family Jean-Christophe, Aline, Mathieu, and Julie,

who I love you.

  

Robert Wohnoutka is an independent software developer with over 20 years of software

development experience. He currently has 11 iPhone apps in the Apple app store.

  Robert is a former Apple employee where he learned the importance of ease-of-use which is the first rule he applies in all the apps that he develops. He also has over 20 years of Product Marketing experience with high-tech products where the ease-of-use aspect was his guiding light as he helped companies develop and introduce new technologies into the hands of consumers. My Walks is a good example of an app Robert developed where he applied the ease-of-use principal to a GPS-based walking application. This app only requires the user to tap a Start button to start the walk and the app will automatically detect the end of the user's walk

should the user forget to tap the End button. My Walks was featured in the Best Mobile Apps

2013 book by Jeremy J. Warner and published by Portrait Health Publishing Inc. Robert has also developed a version for bicycling named My Bike Rides and a version for skiing named My Ski Runs. Robert has developed a number of very easy to use money management apps including EZ Adder, EZ Adder II, EZ Balances, EZ Balances II, and EZ2Compare2. He also develops customized apps including an iPhone app for his dentist's clients called Nikki Green DDS.

  

Support files, eBooks, discount offers and more

You might want to visit

  

  or support files and downloads related to your book. Did you know that Packt offers eBook versions of every book published, with PDF and ePub and as a print files available? You can upgrade to the eBook ver book customer, you are entitled to a discount on the eBook copy. Get in touch with us at or more details.

  

  At ou can also read a collection of free technical articles, sign up

  

  for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. TM

  

  Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.

  Why Subscribe? f Fully searchable across every book published by Packt f Copy and paste, print and bookmark content f On demand and accessible via web browser

  Free Access for Packt account holders If you have an account with Packt at , you can use this to access

  

  PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

  

This book is dedicated to:

To my favorite uncle Benjamin Jacob Daniel, for always making me smile and for

inspiring me to work hard and achieve my dreams, I miss you a lot.

Chan Ban Guan, for the continued patience, encouragement and support,

and most of all for believing in me during the writing phase of this book.

To my family for always believing in me and for their continued love and support.

To my niece Ava Madison Daniel thank you for continually bringing joy to our family.

  

To the late Steve Jobs, you will always be an inspiration and a guide towards

perfection. Thank you for all the amazing things you've brought to our lives.

  

May you rest in peace.

This book would not have been possible without your love and understanding.

  

I would like to thank you from the bottom of my heart.

  Table of Contents

Chapter 1: Getting and Installing the iOS SDK Development Tools

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  Table of Contents

  Chapter 3:

  

  

  

  

  

  

  

  

  

Chapter 4:

  

  

  

  Chapter 5:

  

  

  

Chapter 6:

  Table of Contents

  

Chapter 7

  

  

  

  

Chapter 8:

  

  

  Chapter 9:

  

  Table of Contents

Chapter 10: Packaging and Deploying Your Application 323 Introduction 324 Setting up your iOS development team 324 Creating the iOS development certificate 329 Obtaining the development certificate from Apple 331 Registering your iOS devices for testing 335 Creating your application App IDs

  

  

Appendix:

  

  

  Preface The Xcode 4 Cookbook provides you with the skills and knowledge, and practical recipes on how to go about developing useful applications that can be used within the industry. By using this cookbook's step-by-step style approach, presenting examples in the style of recipes, allowing you to go directly to your topic of interest, or follow topics throughout a chapter to gain in-depth knowledge, you will gain the skills needed to develop some stunning applications. This cookbook is a practical guide featuring over 100 recipes that show you how to build your own fun and exciting iOS applications by integrating iCloud, Facebook, Mobile core services, Core Image and Media Player Frameworks, and the Core Graphics and Core Motion frameworks, that will enable you to enhance your applications to create some amazing image and transition effects using the built-in image filters. In this book, I have tried my best to keep the code simple and easy to understand. I have provided step-by-step instructions with loads of screenshots at each step to make it easier to follow. You will soon be mastering the different aspects of iOS 6 programming, as well as mastering the technology and skills needed to create some stunning applications. Feel free to contact me at for any queries, or if you just

  geniesoftstudios@gmail.com

want to drop by and say "Hello". Any suggestions for improving this book will be highly regarded.

  Preface What this book covers

  

Chapter 1, Getting and Installing the iOS SDK Development Tools, introduces the developer

to the Xcode developer set of tools, as well as the capabilities of the iOS Simulator and each

of the layers contained within the iOS architecture, before finally looking at how to create a simple iOS application.

  Hello World

  

Chapter 2, User Interfaces – Creating the UI, introduces the concept of views and how they

are part of a complete iOS application. Exploring a large number of various view components,

you will create different applications that will help you understand how each component works. We will also learn about the Model View Controller (MVC) pattern and how to use it

to create applications suitable for enhanced user experience. Through this chapter, you will

also learn about the most useful controllers, which will be part of many of your projects in the future.

  

Chapter 3, Using Storyboards, gains an understanding of what Storyboards are and how we

can apply the various transitions between views. We will take a look into how we are able to

create and configure scenes and storyboard files, to present these programmatically. Finally,

we will learn how to integrate Twitter capabilities into our application to tweet photos and standard messages using the new iOS 6 frameworks.

  Social

  Chapter 4, Using Xcode Instruments, focuses on how to effectively use Instruments within

our applications to track down memory leaks and eliminate bottlenecks that could potentially

cause our application to crash on the user's iOS device. We will also take a look at how to

add and configure instruments, as well as learn how to use the System Trace Instrument to

monitor system calls and track down performance issues within the application.

  Chapter 5, Working with the Location Services and the MapKit Frameworks, introduces a detailed guide for using the built-in location services to create applications that provide location information to the user. You will not only learn how to use the GPS hardware, but also how to display maps and layout information using Overlays.

  Chapter 6, Storing Documents within the Cloud , introduces you to the benefits of using

iCloud, and how to incorporate iCloud functionality into your applications to store and retrieve

files, and its data through the use of the Storage APIs. This chapter will also give you some

insight into how to go about handling file version conflicts when multiple copies of the same

file are being updated on more than one iOS device.

  Chapter 7, Working with the Different Multimedia Resources, focuses on teaching you to create applications that capture, reproduce, and manage multimedia content through the device's hardware. You will not only learn to use the camera to capture images and videos

but also how to play back and record audio. We will also learn how to implement the different

image filter effects and transition animations to produce a water ripple effect, as well as learning how to incorporate Airplay functionality into our application.

  2

  Preface

  Chapter 8, Working with the CoreData and GameKit Frameworks, focuses on showing you

how to use the Core Data framework to create a simple Books Library application, to directly

interface with a SQLite database, to create and store book details. We will also look at how to

incorporate Bluetooth functionality, so that you can send book details to another iOS device,

and have this information received wirelessly and stored within the database at the other end.

  

Chapter 9, Creating a Social Networking App with the Facebook iOS SDK, shows you how to

download the Facebook SDK and register your application with Facebook. It also shows you

how to use the Facebook APIs to integrate Facebook functionality into your app, using the

Single Sign On (SSO) feature. This provides users the ability to sign into your application using

their Facebook identity, so that they can submit notification requests, or submit content to

their wall. We will learn how to use the Open Graph API and Facebook Query Language (FQL)

to pass SQL Query like syntax to retrieve information about the current user, and learn how to cleanly handle Facebook errors within our iOS applications.

  Chapter 10, Packaging and Deploying Your Application, walks you through the required steps to deploy your finished application to devices, as well as showing you how to prepare and distribute it to the App Store. We will also take a look at how to create and obtain provisioning profiles for both development and distribution.

  Appendix, Exploring the MultiTouch Interface, discusses how to create applications that are fully aware of their surrounding environment, through the device's sensors. You will learn to adjust the user interface according to device orientations and how to respond to accelerometer and gyroscope events. You will also learn about the built-in shake gesture, and how to go about responding to the shake motions.

  What you need for this book

The minimum requirement for this book is an Intel-based Macintosh computer running Mac

OS X Snow Leopard (10.6.*) or Lion (10.7.*). I would highly recommend upgrading to Lion or Mountain Lion, as there are many new features in Xcode that are available only to these two operating systems.

  We will be using Xcode 4.6.2, which is the integrated development environment used for creating applications for iOS development. Almost all projects you will create with the help of this book will work on the iOS Simulator. However, some projects will require a device to work correctly. You can download the latest version of Xcode at the following link:

  http://developer.apple.com/xcode/

  3

  Preface

  If you ever wanted to build applications that interact with Facebook, iCloud, Core Location, and the Core Motion frameworks into your own applications then this book is for you. You should have a good knowledge and programming experience with Objective-C and have used Xcode 4 and iOS 5.

  Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of

information. Here are some examples of these styles, and an explanation of their meaning.

  Code words in text are shown as follows: "Whenever compiler directives are used in Objective-C, they are responsible for responding to and executing the associated snippets of code encapsulated within the

  #ifdef

  and

  #endif tags".

  A block of code is set as follows:

  • (IBAction)btnTapHere:(id)sender { NSString *greeting = [NSString stringWithFormat:@"Welcome To Xcode 4 Cookbook series %@ %@",txtFirstname.text, txtSurname.text]; lblOutput.text = greeting; lblOutput.font = [UIFont boldSystemFontOfSize:21]; lblOutput.textColor = [UIColor blueColor]; }

  

When we wish to draw your attention to a particular part of a code block, the relevant lines

or items are set in bold:

  // SecondViewController.h // TwitterExample // // Created by Steven F Daniel on 21/09/12.

  // Copyright (c) 2012 GenieSoft Studios. All rights reserved. #import <UIKit/UIKit.h>

  @interface SecondViewController : UIViewController<UIAlertViewDelegate>

  @end

4 Who this book is for

  Preface New terms and important words are shown in bold. Words that you see on the screen, in

menus or dialog boxes for example, appear in the text like this: " To continue execution of your

application, click on the Continue program execution button".

  Warnings or important notes appear in a box like this.

  Tips and tricks appear like this.

  Reader feedback Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply send an e-mail to , and

  feedback@packtpub.com mention the book title via the subject of your message.

  If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on .

  www.packtpub.com/authors

  Customer support Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

  Downloading the example code You can download the example code files for all Packt books you have purchased from your . If you purchased this book elsewhere, you can

  

  

  

  and register to have the files e-mailed directly to you.

  5

  Preface Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen.

  

If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be

grateful if you would report this to us. By doing so, you can save other readers from frustration

and help us improve subsequent versions of this book. If you find any errata, please report them

by visiting

  , selecting your book, clicking on

  http://www.packtpub.com/submit-errata

  the erratasubmissionform link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or

added to any list of existing errata, under the Errata section of that title. Any existing errata can

be viewed by selecting your title from .

  http://www.packtpub.com/support

  Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt,

we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

  

Please contact us at with a link to the suspected pirated material.

  

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

  Questions You can contact us at if you are having a problem with any

  questions@packtpub.com aspect of the book, and we will do our best to address it.

  6

  1 Getting and Installing the iOS SDK Development Tools

  In this chapter, we will cover: f Downloading and installing the iOS SDK f Using Xcode to create an iOS project f Using Interface Builder to create the user interface f Building the user interface for our application f Creating outlets to Interface Builder objects f Creating actions that respond to user actions f Compiling your project f Using the iOS Simulator to test your applications f

  Configuring and using compiler directives f Debugging your iOS applications using Xcode f Using the Clang Static Analyzer to examine your code

  Getting and Installing the iOS SDK Development Tools Introduction

  Welcome to the exciting world of iOS programming using iOS 6. This latest release of the mobile operating system is packed with some great new features and improvements, and comes with over 200 new features as well as an updated SDK featuring over 1,500 new development APIs that can be incorporated into your applications.

  In this chapter, we will look at what integrated development environments (IDEs) and

software development kits (SDKs) are needed to develop applications for the iOS platform,

Apple's operating system for mobile devices. We will explain the importance of each tool's

role in the development cycle, before finally developing our first application. The tools that are

required to develop applications for the iOS platform are explained, as follows:

f An Intel-based Mac computer running the Snow Leopard (10.6.*), Lion (10.7.*),

or OS X Mountain Lion (10.8.*) operating system: The essential development tools cannot be installed on any other computer platforms, so if you are running another processor type (such as the older Mac G4 or Mac G5), you're out of luck. f iOS 5 SDK (or higher): In order to download the Apple iOS SDK, you must be registered as an Apple developer. The iOS SDK consists of the following components:

  Component Description Xcode This is the main IDE that enables you to develop, edit, and debug native applications for the iOS and Mac platforms using the

  Objective-C programming language. iOS Simulator This is a Cocoa-based application that enables you to debug your iOS applications on the computer, without the need of having an iOS device. There are many iOS features that simply won't work within the Simulator, so a device is required if an application uses those features, that is, the Core Location and MapKit frameworks. Instruments These are the analysis tools that help you optimize your applications and monitor for memory leaks during execution of your application at real time. Dashcode This enables you to develop web-based iOS applications and dashboard widgets.

Chapter 1 Downloading and installing the iOS SDK This recipe includes information on how to sign up to the Apple Developer Program, as well as how to download and install the necessary tools needed to develop applications using Xcode. Getting ready Before you can start building iOS applications, you must first join up as a registered user

  of the iOS Developer Program in order to download all of the necessary components to our

computer. At the time of writing, the latest version is 4.5.2, and iOS SDK's latest version is 6.x.

The registration process is free, and provides you access to the iOS SDK and other developer

resources that are really useful for getting you started.

  The following short list outlines some of the things that you will be able to access when you become a member of the iOS Developer Program: f Helpful getting started guides to help you get up and running quickly f Helpful tips that show you how to submit your apps to the App Store f Ability to download current releases of the iOS software f Ability to beta test releases of iOS and the iOS SDK f Access to the Apple Developer Forums

  Whether you are developing applications for the iPhone or iPad, these use the same operating system (OS) and iOS SDK to allow you to create universal applications that will work with both the iPhone and iPad running on iOS 4.3.* and above.

  Getting and Installing the iOS SDK Development Tools How to do it...

  To prepare your computer for iOS development, you will need to download and install the necessary components in the following order:

  1. To sign up to the iOS Developer Program, you will need to go to

  https://developer.apple.com/devcenter/ios/index.action

  and then click on the Log in button to proceed, as shown in the following screenshot:

  2. Once you have signed up, you will then be able to download the iOS SDK and proceed with installing it onto your computer.

  3. Xcode can also be obtained from the Mac App Store at the following link , depending

  http://itunes.apple.com/us/app/xcode/id497799835?mt=12

  on whether you have chosen the version for Mac OSX Lion. The installation procedure in the remaining steps shows how to go about installing the iOS development tools for Snow Leopard.

  4. Once you have downloaded the SDK for Snow Leopard, you can proceed with installing it. You will be required to accept a few licensing agreements. Once you have done that, all you need to do is select the destination folder of the installation and click on the Continue button.

  

5. If you select the default settings during the installation phase, the various tools

will be installed in the folder. The installation

  /Developer/Applications

  

process takes you through the custom installation options screen, as shown in

the following screenshot:

These options give you a little more control over the installation process. For example, you are

able to specify the folder location in which you would like to install Xcode, as well as settings

for a variety of other options.

  Getting and Installing the iOS SDK Development Tools How it works...

  

Now that everything has been installed and is ready to go, our next step is to take a look at

what each component within the Xcode and iOS SDK is needed for. As mentioned in the Introduction section of this chapter, the iOS SDK is made up of three important components. The main component, Xcode IDE, is Apple's IDE that allows for

developing applications for the iOS and Mac platforms, and uses Objective-C as the default

programming language. This environment allows for better integration and editing of source code, and building,

compiling, and debugging your applications. It contains a number of tools that can help with

diagnosing issues with your iOS applications. The topic on instruments, will be covered later

on in this book. The IDE contains a device information window, called Organizer – Devices,

which is shown in the following screenshot:

Chapter 1 This screen is necessary to install the various certificates and provisioning profiles that are

  required for deploying an application onto a device for testing, or distribution through the

Apple App Store. Using the Organizer – Devices window, you can view debugging information

of your applications, crash logs, as well as the ability to take screenshots from the device.

f Interface Builder: This is the user interface designer that is integrated within the

  IDE. Interface Builder provides you with all the necessary functionality to construct an application's user interface. All of your objects are stored within one or more resource files and contain the associated relationship to each of the objects. Any changes that

you make to the form design are automatically synchronized back to your code.

f iOS Simulator: This is an extremely useful tool that acts as a testbed for your applications without the need for using an actual device, whether an iPad or any other iOS device. Whenever you build and run your application, Xcode installs your application on the iOS Simulator and launches this for you automatically. The iOS Simulator has the capability of simulating the different iOS versions, and this can become extremely useful if your application needs to be installed on different iOS platforms, as well as testing and debugging errors reported in your applications when run under the different iOS versions.

  There's more… The following list provides you with the links that contain the tools and information for installing them: f Apple iOS Developer Portal:

  https://developer.apple.com/devcenter/ ios/index.action

  f Apple Developer Tools information:

  https://developer.apple.com/ technologies/tools/whats-new.html

  See also f The Compiling your project recipe f The Debugging your iOS applications using Xcode recipe f The

  Using provisioning profiles to install an iOS app on an iOS device recipe in

  Chapter 10, Packaging and Deploying Your Application f The Submitting an application to the App Store using iTunes Connect recipe in

  Chapter 10, Packaging and Deploying Your Application

  Getting and Installing the iOS SDK Development Tools Using Xcode to create an iOS project

  In this recipe, we will see how easy it is to create our very first iOS application project using the Xcode IDE.

  Getting ready

Now that we have all of the preliminary components installed, we will start to create our very

first HelloWorld project using Xcode.

  How to do it...

  To begin with creating a new Xcode project, perform the following simple steps: 1. Launch Xcode from the folder.

  /Developer/Applications 2. Choose Create a new Xcode project, or File | New Project.

  3. Select Single View Application from the list of available templates, as shown in the following screenshot:

Chapter 1 4. Click on the Next button to proceed to the next step in the wizard.

  5. Next, enter as the name of your project.

  HelloWorld 6. Select iPhone from under the Devices drop-down menu.

  7. Ensure that the Use Storyboards checkbox has not been checked.

  8. Ensure that the Use Automatic Reference Counting checkbox has been checked.

  9. Ensure that the Include Unit Tests checkbox has not been checked.

  The Company Identifier for your app needs to be unique. Apple recommends that you use the reverse domain style (for example, com.domainName.appName).

  10. Click on the Next button to proceed to the next step in the wizard.

  11. Specify the location where you would like to save your project.

  12. Then, click on the Create button to save your project at the specified location.

  Getting and Installing the iOS SDK Development Tools Once your project has been created, you will be presented with the Xcode development

environment, along with the project files that the template created for you. If you want, you can

build and run the application. The iOS Simulator will start and show a blank white screen.

  How it works...

  

Now that we have created our HelloWorld project, let's take the time to see what the template

wizard created for us. When Xcode creates a new iOS project, it also creates a series of files. Depending on what options have been selected during this process may result in some additional files being created.

  The following screenshot shows a list of the essentials files that form part of an iOS project:

Chapter 1 The following are the important

  files to take a note of: f

  main.m

  f and

  AppDelegate.h AppDelegate.m

  f and

  ViewController.h ViewController.m

  f

  HelloWorld-info.plist

  main.m The main function is where the runtime lifecycle of your program starts and ends. The function runs the loop that is responsible for sending

  UIApplicationMainstarts

  class, and contains the various notifications to the application through the AppDelegate

event handlers that can be overridden. This function takes four parameters and uses them to

initialize the application.

  // main.m // HelloWorld // // Created by Steven F Daniel on 18/12/11.

  // Copyright (c) 2012GenieSoft Studios. All rights reserved. #import <UIKit/UIKit.h> #import "AppDelegate.h" int main(int argc, char *argv[]) { @autoreleasepool { returnUIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } }

  There's more… You will notice that within our main function, it contains , which is an

  @autoreleasepool

  

object to support the memory management system for your iOS device. Next, we are including

the and parameters. Given that all iOS applications run within a graphical

  argc argv[]

  interface and don't run from the command line, these are simply here so that they conform to the standard ANSI C coding practices.

  Getting and Installing the iOS SDK Development Tools Understanding application delegates

The application delegate implements how your program should react at critical points during

the application lifecycle. The delegate is responsible for initializing a window at application

startup and cleaning up at program termination. This class is responsible for causing the main

view controller to be displayed, as well as handling application responsiveness whenever your

application suspends or resumes.

  Understanding the ViewController class

This file implements the views functionality and contains the class methods that correspond

to the view that is being loaded, as well as the method declarations that can be overridden.

  In the following table, we describe some of the methods that are contained within this class:

  Method name Description viewDidLoad This method is called whenever the view controller is loaded, and is used to set up any additional objects. viewDidUnload This method is called whenever the view is unloaded from memory. viewWillAppear This method is called whenever the view is ready to appear on the devices' screen, or that it has fully appeared already. viewDidAppear This method is called whenever you want to perform a particular action, once the view has fully appeared on screen, such as performing some sort of transition animation or sound. This method is normally used whenever you shouldAutorotateTo

  InterfaceOrientation want your application to support multiple screen orientations, that is, landscape or portrait.

  Understanding ViewController.xib

The XIB file may not be visible depending on whether you selected to use storyboards during

the creation of your project. The XIB file is basically an XML file with a specific structure that

is readable from Interface Builder, and contains various information about the user interface,

such as the type of controls it contains, their properties, outlets, and so on.

  Understanding HelloWorld-info.plist

This file is basically the applications' settings file and contains the properties and their values

that define the various settings for an iOS application. These settings have information relating

to the device orientations that it will support, the application icon and the supported iOS

versions, as well as what devices the application can be installed on. The following screenshot

shows the structure of this file when it has been double-clicked in the Xcode editor:

Chapter 1 See also

  f The Building the user interface for our application recipe f The Creating outlets to Interface Builder objects recipe

f The Adding and customizing views recipe in Chapter 2, User Interfaces – Creating

the UI

  Using Interface Builder to create the user interface In this recipe, we will familiarize ourselves with the Interface Builder application. Interface

Builder is a visual tool that enables you to design the user interface for your iOS applications.

Using Interface Builder, you are able to drag-and-drop views and objects onto your canvas

area from the libraries pane. These objects can then be connected using outlets and actions

so that they can programmatically interact with your code.

  Getting and Installing the iOS SDK Development Tools How to do it…

  

To display our view controller within Interface Builder and the Xcode environment, perform the

following simple steps:

1. Select the ViewController.xib file from the project navigator window.

  2. From the Xcode toolbar, select the viewing options, as shown in the following screenshot:

In the preceding screenshot, this shows what Interface Builder looks like when an XIB file has

been chosen from the project navigator window.

  How it works… Whenever you use Interface Builder to design a user interface, any objects that have been used from the library pane will be connected to the Xcode project that they belong to.

Chapter 1 As you can see from the preceding screenshot, the Interface Builder workspace is divided into

  three main areas. The following table provides a brief description of which area is used for what functions:

  Area name Description Navigation area This area displays all files associated with the project. Editor area This area is where we start to design our user interface from. Inspector pane This area is where we can configure each of our objects. Library pane This area is where we can locate objects and drag them onto our view. Such objects are the

  UILabel, UIButton, UITextField, and so on.

  There's more… You may have noticed the section called Simulated Metrics located on the Attributes tab

within the inspector pane window. This area shows you how our interface will look like within

the designer, and eventually how it will look like when it is deployed and run on the iOS device.

Here you can specify whether your interface will have a status bar, toolbar, or even a navigation bar. It is worth mentioning that, if you set the Status Bar option to None, it does not mean that our application will start without a status bar.

  The status bar is the bar that appears at the top of the device's screen and displays certain types of information to the user, such as the current time, battery status, carrier name, and so forth.

  See also f The Building the user interface for our application recipe f The Creating outlets to Interface Builder objects recipe

f The Adding and customizing views recipe in Chapter 2, User Interfaces – Creating

the UI

  Getting and Installing the iOS SDK Development Tools Building the user interface for our application

  In this recipe, we will learn how to go about building our user interface and how to add controls.