Preface What You Need to Start iOS Development Chapter 1: Say Hello World .......................................................................................................................... 8 Chapter 2: Hello World App Explained ...................................................................................................... 25 Chapter 3: Creating Simple Table ............................................................................................................... 32 Chapter 4: Customizing Table View Using Prototype Cell ......................................................................... 49 Chapter 5: Table Row Selection .................................................................................................................. 69 Chapter 6: Table Row Deletion and Model-View-Controller ..................................................................... 79 Chapter 7: Enhance Table App With Property List .................................................................................... 86 Chapter 8: Launch Image ............................................................................................................................97 Chapter 9: Navigation Controller .............................................................................................................. 105 Chapter 10: Passing Data Between View Controllers ................................................................................ 115 Chapter 11: Tab Bar Controller and Web View ......................................................................................... 124 Chapter 12: Object Oriented Programming - An Introduction ................................................................. 141 Chapter 13: Beautify the Recipe App ......................................................................................................... 152 Chapter 14: Adding Search Bar ................................................................................................................. 165 Chapter 15: Grid Layout Using UICollectionView .................................................................................... 178 Chapter 16: UICollectionView Part 2 ........................................................................................................ 189 Chapter 17: UICollectionView Part 3 ........................................................................................................ 201 Chapter 18: Introduction to Core Data ..................................................................................................... 217 Chapter 19: Core Data Part 2 .................................................................................................................... 233 Chapter 20: Localization .......................................................................................................................... 243 Chapter 21: Static Table View ................................................................................................................... 259 Chapter 22: Building a Simple RSS Reader App ...................................................................................... 268 Chapter 23: Building a Simple Camera App ............................................................................................ 280 Chapter 24: Video Recording and Playback ............................................................................................. 288 Chapter 25: Local Notification .................................................................................................................. 298 Chapter 26: Introduction to UIPageViewController ................................................................................ 307 Chapter 27: Slide-out Sidebar Menu ........................................................................................................ 325 Chapter 28: Adding a Cloud Backend Using Parse .................................................................................. 343 Chapter 29: Parse Cloud Part 2 ................................................................................................................ 362 Chapter 30: AirDrop ................................................................................................................................. 375 Bonus Chapter: Objective-C Basics .......................................................................................................... 385


Copyright © 2014 All rights reserved. Please do not distribute or share without permission. No part of this book or corresponding materials (such as images or source code) may be distributed by any means without prior written permission of the author. All trademarks and registered trademarks appearing in this book are the property of their respective owners.


Despite I had years of programming experience. I love to hear from you. Everyone are talking about apps and want to build one. practice and practice. This turned out to be a great learning experience. You have to practice. If you’re planning to read this book in bed and expect to understand app development. It’s the first time in the computing history that any developer can create an app and deliver it to millions of devices all on your own. Thanks for picking up this the best way to learn a new programming language is to get your hand dirty. It’s truly an amazing experience to develop an app. Simon Ng Founder of appcoda. You can’t just read a book and teach yourself Japanese (or other languages). this book is not for you. The iOS and App Store has changed the way we distribute and consume software. it’s just like most of you. Are you ready for that? When I first created my iOS app. This book will take you through a similar learning adventure and teach you how to build your first apps on iOS 7. It’s similar to learning a foreign language. That’s the same for studying a new programming language. Yet this is the very first time I put up my own product and make it available globally. drop me email at simonng@appcoda. I hope you’ll enjoy reading it and that you’ll soon put up your first iOS app on App Store. I have been programming for over 10 years and developed various kinds of business systems. debug and build some real apps. You’ll get a lot of hands-on exercises and projects. There are a lot of works to do but it would be a fantastic experience and you’ll master the fundamentals of iOS 7 programming along the way. From my experience. So I decided to create a real app. If you’d like to share with me about your first iii .PREFACE In September 2011. This is a great opportunity for all developers. It’s a book for those who take actions. It took me several weeks to grasp the basics of iOS programming and developed the app. I knew nothing about Objective-C and iOS programming. however. I released my first iPhone app on the App Store. You’ll need to code. I can’t tell in words how happy when my app went live and got thousands of downloads.

1 SAY HELLO WORLD I hope you have configured your development environment properly with Xcode installed. check out the previous chapter about what you need to begin iOS programming. If you haven’t done so.0 to work on all exercises in this book. World” on the display of a device. In this 4 . It has become the traditional program for first-time learner to create. It’s a very simple program that usually outputs “Hello. We’ll use Xcode 5. You may have heard of “Hello World” program if you have read any programming book before.

I don’t want to scare you away. Nothing complex but it helps you kick off your iOS programming journey. That’s it. You’ll learn how to create a Xcode project and create user interface with the built-in interface builder.Hello World It’s very simple and shows only a “Hello World” button. • It also gives you a basic introduction of the Xcode environment.chapter. the app prompts you a message. Take a Look at Your First App Before we go into the coding part. Despite its simplicity. let’s follow the programming tradition and create a “Hello World” app using Xcode. When tapped. 5 . the programming language of iOS. • Lastly. • You’ll learn how to compile a program. it makes you think programming is not difficult. Your First iPhone App . let’s first take a look at our version of the “Hello World” app. the “Hello World” program serves a few purposes: • It gives you a better idea about the syntax and structure of Objective C. build the app and test it using the Simulator. The final deliverable will look like this: Figure 1-1.

and that's the best way of learning things.h and .CHAPTER 2 HELLO WORLD APP EXPLAINED “When you learn through coding. . It’ll be good for you to understand some of the Objective-C syntax and the inner workings of the app. they 6 .” ~ Mitch Resnick Isn’t it easy to build an app? I hope you enjoy reading the first chapter and already created your first iPhone app. So far you follow the step-by-step procedures to build the Hello World app.xib. let’s step back and have a closer look at the Hello World app. You're learning it in a meaningful context.m file? • What are those “ugly” code inside “showMessage”? What do they mean?! • What actually happens after you taps the “Hello World” button? How does the button trigger the “showMessage” action? • How does the “Run” button in Xcode work? I want you to focus on exploring the Xcode environment so I didn’t explain any of the above questions. But as you go through the previous chapter. Before we continue to build another app. [you're] coding to learn. For some technical concepts. Yet it’s essential for every developer to understand the inner details behind the code and grasp the basic concept of iOS programming. you may come across these questions: • What are those .

what are those . I believe most of us don’t know how the remote communicates with the TV set and controls the speaker volume.m extension are the implementation files. But for now. Do you know what happens behind the scene when pressing the “Volume” button? Probably not. to put in analogy that you can better understand both terms. To increase the speaker volume. you’ll get better understanding about iOS programming.h and . We’ll talk about them later. Well. Like most of the programming languages. (If you expand the “Supporting Files” folder. As you click on the . What we 7 . they’re Interface Builder files that store the application’s user interface (UI).xib. Figure 2-1.m – Files with . Don’t worry. you press the “Volume +” button. let’s consider a TV remote. let’s forget about them first. you simply key in the channel number.may be a bit hard to understand particularly you have no programming background. This is just a start.h and . however.xib extension. To switch channel. you should find three main types of files – .xib. Xcode automatically switches to the Interface Builder for you to edit the UI of the app via drag-and-drop.) . . Interface Builder. Just try your best to learn as much as possible. Let me ask you.h extension refers to the header files while those with . It’s convenient to control the volume of a TV set wirelessly with a remote.m. Interface Builder in Xcode .xib file. the source code of Objective-C is divided into two parts: interface and implementation.m files? Under the Project Navigator. you’ll find other file types such as plist and framework. As you move on and write more code in later chapters.xib – For files with . .h and . Header and Implementation Files First.

what’s a Table View in iPhone app? Table view is one of the common UI elements in iOS apps. Most apps.” ~ Confucius Is it fun to create the Hello World app? In this chapter. in some ways. Another example is the Mail app. First. The best example is the built-in Phone app. make use of Table View to display list of data. 8 . Table View allows you to present the data in the form of images. Your contacts are displayed in a table view. It uses Table View to display your mail boxes and emails. The YouTube and Airbnb apps are great examples for the usage.CHAPTER 3 CREATING SIMPLE TABLE “Life is really simple. we’ll work on something more complex and build a simple app using Table View. but we insist on making it complicated. Not only designed for showing textual data.

open your Xcode and code! This is the best way to study programming.Figure 3-1. Stop reading. Once launched Xcode. let’s get our hands dirty and create a simple app. Don’t just read the chapter if you’re serious about learning iOS programming. Sample Table View from Snapguide. create a new project using the “Single View application” temple. Digg and Airbnb Creating a SimpleTable Project With an idea of table view. 9 .

4 CUSTOMIZE TABLE VIEW USING PROTOTYPE CELL In the last chapter. we’ll beautify the table cell and make the app look better. Rebuild the same app using prototype cell 2. we created a simple table view app to display a list of recipes with a predefined image. There are a number of changes and enhancement we’ll work on together: 1. In this chapter. Display individual image for each recipe instead of showing the same thumbnail for all recipes 3. Custom the table view instead of using the default style of table view cell 10 .

You can simply design the cell right inside the Storyboard editor. The introduction of prototype cell. Meanwhile we’ll show you another way to create table view in Xcode. CustomTable Project Options 11 . we used the table view from Object Library to create the table view. Building Table View Using Prototype Cell Since the release of iOS 5. Previously. Xcode introduced a new table element called Prototype Cell. allows developers to customize a table cell easily. simplifies the way of creating and designing table cells. You can create table view without using prototype cell. Apple introduced Storyboarding that simplifies the way to design user interfaces for your app. Along with Storyboard. Will it be easier? It may not be easier if you just want to create a simple table. Figure Figure 4-1. It. just like you did in the previous chapter. just like what we did earlier. fire up your Xcode! Once launched Xcode.You may wonder why we need to rebuild the same app. however. however. Name the project as “CustomTable” and fill in all the required options for the Xcode project. But first let’s see how we use prototype cell to re-create the same Simple Table app. To begin. We’ll go into the details of cell customization. There are always more than one way to do things. create a new project using the “Single View application” template.

5 TABLE ROW SELECTION I believe you should manage to create a simple table view app and understand how to custom a table cell. But how do we know when someone taps or selects a table row (or cell)? This is what we’ll go through in this chapter and see how you can handle cell selection. So far we focus on displaying data in table view. And we’ll add a couple of enhancements: 12 . We’ll build on the CustomTable app that we’ve worked on in the previous chapter.

apple. right? Let’s get started.• Display an alert message when user taps a table cell • Display a check mark when user selects a table cell Easy. Handling Table Row Selection Before we change the code. we declared two delegates (UITableViewDelegate.h> @interface SimpleTableViewController : UIViewController <UITableViewDelegate.h: #import <UIKit/UIKit. the UITableViewDelegate deals with the appearance of the UITableView. it also applies this design concept. On the other hand. UITableViewDataSource) in the SimpleTableController. we’ll make use of the UITableViewDelegate and implement the required methods for handling the selection. it depends on another object to handle it. The UITableViewDataSource delegate. When you look at the UITableView class. This is usually known as separation of concern in software design. you may wonder: How do we know which methods in UITableViewDelegate need to implement? There are two ways to access the documentation. defines methods that are used for displaying table data. both delegates are known as protocol in Objective-C. It’s very common to come across various delegates in iOS programming. You can always refer to the Apple’s official iOS developer reference (https://developer. Understanding UITableViewDelegate When we first built the Simple Table View app in Chapter 3. that we’ve learnt. You have to conform with the requirements defined in these protocols in order to build a UITableView. Whenever an object needs to perform a certain task. handles the table row selection. Each delegate is responsible for a specific role or task to keep the system simple and clean. as well and search for the API 13 . The two delegates are catered for different purpose. UITableViewDataSource> @end As explained in the earlier chapters. Obviously.

Again. I have to introduce you the Model-View-Controller model. there is still one thing left about UITableView.6 TABLE ROW DELETION & MODEL-VIEW-CONTROLLER As mentioned in the previous chapter. which is one of the most quoted design patterns for user interface programming. But before jumping into the coding part. it’s easier than you thought. How can we delete a row from UITableView? This is another common question people raised when building the Simple Table App. 14 .

Concerns are the different aspects of software functionality. MVC shouldn’t be new to you. and presentation objects that are the GUI elements we see on the screen. and continues today allowing many applications to be manipulated through both a graphical and command-line interface. the operations are usually known as business rules. MVC is commonly used and quoted in other programming languages such as In reality. View – view manages the visual display of information. edit and delete are examples of the operations. MVC breaks an user interface into three parts: Model – model is responsible for holding the data or any operations on the data. is what I call Separated Presentation. Here. For example.html#ModelViewController No matter what computer language you learn. and the idea that was the most influential to later frameworks. As the name suggests. 15 . The core idea behind MVC is to clearly separate user interface into three areas (or groups of objects) that each area is responsible for a particular functionality. Add.” By Martin Fowler http://www. The concept encourages developers to break a big feature or program into several areas of concern that each area has its own responsibility. they should also be able to support multiple presentations. Not limited to iOS programming. possibly simultaneously. This approach was also an important part of the Unix culture. one important concept that makes you become a better programmer is Separation of Concerns (SoC).martinfowler. If you come from other programming backgrounds. model-view-controller (MVC) is another example of SoC. The idea behind Separated Presentation is to make a clear division between domain objects that model our perception of the real world. The concept is pretty simple. The model can be as simple as an array object that stores all the table data.You can’t escape from learning Model-View-Controller (MVC for short) if you’re serious about iOS programming. Domain objects should be completely self contained and work without reference to the presentation. UITableView shows information in a table view format. Understanding Model-View-Controller “At the heart of MVC. The delegate pattern that is commonly found in iOS programming we explained in the earlier chapters is one of the example of SoC.

MVC Model Illustrated Using Simple Table as Example The recipe information that are stored in separate array objects is the Model. UITableView actually asks the Controller for the data to display. For example. It’s responsible for all the visuals (e. Each table row maps to an element of the recipe arrays. font size and type). After that.Controller – controller is the bridge between model and view. user taps a delete button in the view and controller. If you turn the concept into visual representation. The app displays a list of recipes in the table view. in turn. tap) into appropriate action to be performed in the model. that in turn. here is how the table data is displayed: Figure 6-1. color of the table rows.g.g. To help you better understand MVC. it also requests the view to refresh itself to reflect the update of the data model. picks the data from the model. triggers a delete operation in the model. When display table data. The UITableView object is the View that is the interface to be seen by the user. let’s use our Simple Table app we developed in Chapter 3 as an example. 16 . The TableViewController acts as the bridge between the TableView and Recipe data model. It translates the user interaction from the view (e.

In real app. What separates the talented individual from the successful one is a lot of hard work. However.e. we’ll make some changes in our simple table app and tweak it to use Property List. In this chapter. the recipe information) and put them in a file or database or somewhere else. This kind of file is commonly found in Mac OS and iOS. and is used for storing simple structured data (e. In brief. it’s not a good practice to “hard code” everything in the code. there is a file type known as Property List. In iOS programming. we used to externalize these static items (i. If you look into the app. application setting).g. I try to keep the thing simple and focus on showing how to create and customize a UITableView.” ~ Stephen King We already built a very simple table app displaying list of recipes. here are a couple of things we’ll cover: • Convert table data from static array to property list • How to read property list 17 . all our recipes are stored in the source code as arrays.CHAPTER 7 ENHANCE TABLE APP WITH PROPERTY LIST “Talent is cheaper than table salt.

@"creme_brelee. the code). @"1.jpg". @"4 hours".jpg". @"Vegetable Curry". @"Noodle with BBQ Pork".jpg". @"vegetable_curry. @"Starbucks Coffee".5 hour". @"5 min". @"1 hour". Does it look better when the table data is stored like this? 18 . @"Green Tea". @"full_breakfast. it would be better to separate the data and the programming logic (i. @"10 min". @"Hamburger".jpg". @"white_chocolate_donut. @"30 min".jpg".jpg".jpg". @"noodle_with_bbq_pork. @"japanese_noodle_with_pork.jpg". nil]. @"Ham and Cheese Panini".jpg". @"8 min".jpg".e. @"instant_noodle_with_egg.Why Externalize the Table Data? It’s always a good practice to separate static data from the code. @"angry_birds_cake. @"Angry Birds Cake". That’s not we want. @"Ham and Egg Sandwich". @"thai_shrimp_cake. Changing the code may accidentally introduce other errors. Apparently. @"20 min". @"ham_and_cheese_panini. @"Thai Shrimp Cake".jpg". recipePrepTimes = [NSArray arrayWithObjects:@"30 min". @"White Chocolate Donut". @"mushroom_risotto. @"ham_and_egg_sandwich. @"Creme Brelee".jpg". @"45 min".jpg". There is nothing wrong doing this. @"20 min". @"Instant Noodle with Egg". you’ll go back to your code and put all the new recipes in the initialization: recipeNames = [NSArray arrayWithObjects:@"Egg Benedict". @"5 min". @"Japanese Noodle with Pork". nil]. But look at the code! It’s not easy to edit and you have to strictly follow the Objective C syntax. @"30 min". nil]. But why? What’s the advantage to put the table data into an external source? Let me ask you. recipeImages = [NSArray arrayWithObjects:@"egg_benedict. @"green_tea. How do you add 50 more recipes in our custom table app we’ve built in chapter 4? Probably. @"hamburger. @"Mushroom Risotto".jpg".jpg".jpg". @"10 min". @"20 min". @"starbucks_coffee. @"30 min". @"Full Breakfast".

How can I add a splash screen for my app? While you may think you need to write code for the splash screen.8 LAUNCH IMAGE Before moving onto another detailed chapter about Navigation Controller. 19 . No coding is required. Apple has made it extremely easy to get it done in Xcode. I’d like to first answer a common question when building an app. What you just need to do is to make a couple of configuration in Xcode.

Sample Launch Images Unlike splash screen. Splash screen is commonly found in desktop applications to display branding information. Perceptually. figure 2 shows the launch image of Yahoo’s Weather app. Usually.It’s Launch Image. however. This is the first screen you see when launching an application. though some apps make use of it to display their logos. the primary purpose of launch image is to let user know your app is loading and give users an impression that your app is immediately ready for use. splash screen is an image covering the entire screen and disappears after the main screen is loaded. As an example. you’re not encouraged to use launch image for branding purpose. This kind of startup screen is commonly known as Launch Image. let me first give a brief explanation about it. According to Apple. Below figure shows you a few samples of launch image:! Figure 8-1. it doesn’t use the term “Splash Screen”. it gives a better user experience. In iOS. Not Splash Screen First thing first. 20 . Launch image is especially important for apps that take longer time to launch. for those who are new to programming and haven’t heard of the term “Splash Screen”.

we’ll show you how to use Storyboards to build a Navigation interface and integrate it with table view. We’ll use that project as foundation and build upon it. What’s Navigation Controller? First thing first. Don’t expect any fancy interface or pretty graphic. what’s navigation controller? Like table view. and that voice will be silenced” ~ Vincent Van Gogh In this chapter. We’ll keep tweaking the artwork in later chapters. 21 . That said. In chapter 5. and Contacts. Take a look at the built-in Photos app. It provides a drill-down interface for hierarchical content. YouTube. navigation controller is another UI element you commonly find in iOS app. this doesn’t mean you have to use both together.' then by all means paint. They’re all built using navigation controller to display hierarchical content. we’ve created a demo app that handles table row selection. Usually table view and navigation controller work hand in hand for most of the apps.CHAPTER 9 NAVIGATION CONTROLLER “If you hear a voice within you say 'you cannot paint. We try to keep thing simple and focus on explaining the concept.

Scene and Segue 22 . Storyboard . An example of Navigation Controller . But so far we just layout one view controller in the storyboard for building table view app.Photos App Scene and Segue in Storyboard We’ve built most of the apps by using Storyboard. Storyboard allows you to do more than that.Figure 9-1. Figure 9-2. You can easily embed a view controller in navigation controller and define the transition (known as segues) between various screens simply using point and click.

we built a simple Recipe app with navigation interface.” ~ Mitch Albom Previously. we learnt to use Storyboards to build a couple of things: • Embedded a view controller in a navigation controller • Switched from one view controller to another using segue Yet. You're just passing it on to someone else. we haven’t implemented the detail view which just shows a static label. we left one thing that was not discussed: data passing between scenes (i.C H A P T E R 10 PASSING DATA BETWEEN VIEW CONTROLLERS “Sometimes when you sacrifice something precious. As I said before. The view controller is assigned with the UIViewController class by default. view controllers) with segue.e. let’s take a quick look at what we’ve accomplished. First. Creating a View Controller Class In the previous chapter. we’ll continue to work on this project and polish the app. So far. we created a view controller that serves as the detail view controller of a recipe in the storyboard editor. you're not really losing it. 23 . In this chapter.

Choose “Objective-C Class” under Cocoa Touch as the class template. we do not need to create a separate interface builder file. we extend from it and create our own class (known as the subclass of UIViewController). Make sure you uncheck the option of “With XIB for user interface”.Figure 10-1. The fact is the UIViewController class only provides the fundamental view management model. right-click the “RecipeApp” folder and select “New File…”.UIViewController Let’s revisit our problem. 24 . Name the class as “RecipeDetailViewController” and it’s a subclass of “UIViewController”. instead of using UIViewController directly. There is no variable assigned for storing the recipe name. The label in the view should be changed with respect to the selected recipe. there must be a variable in the UIViewController for storing the name of recipe. Default View Controller . Thus. In the Project Navigator. Obviously. As we’re using Storyboards for designing the user interface. Click “Next” and save the file in your project folder. It corresponds to a blank view.

Normally the tab bar contains at least two tabs and you’re allowed to add up to five tabs depending on your needs.” ~ Henry Ford Last time. 25 . whether at twenty or eighty. we’ll continue to polish our Recipe app and see how you can make use of two other common UI elements in iOS apps. All of them make use of the tab bar controller to display distinct view in each tab. iTunes and TheVerge. The greatest thing in life is to keep your mind young. right? In this chapter. Just take a look at figure 1 that shows a few sample apps including Twitter. we discussed how to pass data between view controllers with segue. It should be easy. TED.C H A P T E R 11 TAB BAR CONTROLLER AND WEB VIEW “Anyone who stops learning is old. Here are what you’re going to learn: • How to Create a Tab Bar Controller • How to Create an About page using UIWebView Tab Bar Controller and UIWebView As usual. You may not be familiar with the term “Tab Bar” but you should come across it in most of the iOS apps. Anyone who keeps learning stays young. let’s first have a brief introduction for Tab Bar Controller and UIWebView.

is a handy component to load web content. let’s back to our Xcode project.Figure 11-1. you want to display a single web page locally in your app or let users access external web pages within your app. In some cases. You can simply embed the UIWebView object in your app and send it a HTTP request to load the web content. you should build a simple recipe app with navigation interface. Sample Apps with Tab Bar Interface UIWebView. Creating a Tab Bar Controller Okay. It’s not fully implemented but just works. Let me first recap what we’ve done. If you’ve followed the previous chapter. 26 . on the other hand.

It’s not a new kind of programming language but a programming concept/technique. you’ve gone pretty far. We’ll further enhance the detail view of the Recipe app as the original detail view was way too plain. I intentionally left it out when I first began writing the book. Did you manage to create your own detail view for the Recipe app? Anyway. By now. we’ll revisit it and show you how to improve the detail screen. But before that. Don’t be scared by the term “Object Oriented Programming” or OOP in short. you should be able to build an iPhone app with tab bar. I have to introduce you the basics of Object Oriented Programming.” ~ Linus Torvalds If you read from the very beginning of the book and have worked through all the projects.C H A P T E R 12 OBJECT-ORIENTED PROGRAMMING “Most good programmers do programming not because they expect to get paid or get adulation by the public. but because it is fun to program. How can we display more information including the recipe image in the detail view? This shouldn’t be difficult if you understand the materials and I intentionally left out that part for you at the time I wrote the chapter. navigation controller and table view using Storyboard. While some programming books start out by introducing the OOP concept. we’ll build on top of what we’ll learn in this chapter and enhance the detail view screen. I want to keep thing simple and show you (even 27 . In the next chapter.

Most importantly. let’s get started. Object Oriented Programming – Some Theory Objective-C is known as an Object Oriented Programming (OOP) language. The UIViewController object is responsible for the view of the app and as a placeholder for the Hello World button. 28 .! ! Okay. on the other hand. OOP is a way of constructing software application composed of objects. That’s the basic concept of OOP. I believe you’re determined to learn iOS programming and you want to take programming skills to the next level. Each object has its own responsibility and objects coordinate with each other in order to make the software work. just because of a technical term. I think it’s time to cover the concept. If you’re still around reading this chapter. The UIButton (i.e. is responsible to display the alert message to user. UIViewController. Here. all these objects work together to create the Hello World app. most of the code you’ve written in the app in some ways deal with objects of some kind. The UIAlertView object. However.without any programming background) how to create an app. I don’t want to scare you away from building apps. In other words. Take the Hello World app that we’ve built at the very beginning as an example. Hello World button) object is responsible to display a standard iOS button on screen and listen to any touch events. UINavigationController and UITableView are some of the objects come with the iOS SDK. Not only you’ve used the built-in objects in your iOS app. the smaller pieces are the objects. So why OOP? One important reason is that we want to decompose a complex software into smaller pieces (or building block) which are easier to develop and manage. UIButton. you’ve created some objects of your own such as RecipeDetailViewController and SimpleTableCell.

This is very simple app. If you haven’t done so.C H A P T E R 13 BEAUTIFY THE RECIPE APP “Beautiful things don't ask for attention. this is the foundation to help you advance into a full-fledge iOS developer. How can we improve it and display more information such as the preparation time. Before we move on. make sure you check out the chapter about Object Oriented Programming. When user taps on any of the recipes. You can’t become a fullfledged iOS developer without learning objects and classes. the app navigates to a detailed view and brings up the recipe name. You have to understand the basics of OOP before you can work on the project. take some time and read through the chapter. You’ve built a simple Recipe app to display a list of recipes.” ~ James Thurber We already showed you how to use segue in storyboard to pass data between different view controllers. we’ll work on it together and make the app even better. 29 . Wouldn’t be great if we further improve the detail view of the app? The original detail view is primitive with the recipe name only. ingredient and the dish photo? In this chapter. But if you understand how it works. however.

Figure 13-1. strong) NSArray *ingredients. Recipe app with improved detail view Not only with improved user interface. we have to update our code to due with it. the app gives user more information about a recipe including a list of ingredients. apparently. let’s first take a look at the final deliverable. First.The Final Deliverable To give you an idea about the improvement. add a new property named ingredients in the Recipe. Adding Ingredients to the Recipe Data With the additional property of ingredients.h: @property (nonatomic. we initialize the Recipe objects with additional ingredients data: .(void)viewDidLoad { 30 .m”. preparation time and a large photo of the recipe. the revamped Recipe app shows detailed information about a recipe with a better look & feel. In the “viewDidLoad” method of “RecipeTableViewController. As you can see from figure 1.

How can you implement a search bar for data searching? In this chapter. it’s not difficult to add a search bar but it takes a little bit of extra work. Well. we will see how to add a search bar to the recipe app. If you haven’t gone through the chapter. 31 . it is common to have a search bar at the very top of the screen. we’ll enhance the recipe app to let users search through the recipe list by specifying a search term. go back and take some time to check it out. With the search bar. We’ll continue to work on the Xcode project we developed in previous chapter.14 ADDING SEARCH BAR In most of the iOS apps using table view.

the results are displayed in a table view that’s created by the search display controller.e. 32 . Enhancing recipe app with a search bar Understanding Search Display Controller You can use search display controller (i. A search display controller manages display of a search bar and a table view that displays the results of a search of data.Figure 14-1. Interestingly. When a user starts a search. the search display controller will superimpose the search interface over the original view and display the search results. UISearchDisplayController class) to manage search in your app.

com/library/ios/#documentation/UIKit/Reference/ UICollectionView_class/Reference/Reference.html) that allows developers to create gridlike layout out of the box. Wouldn’t be great if it can display the recipe in a nice grid view? Since the release of iOS 6. we built a Recipe GRID LAYOUT USING UICOLLECTIONVIEW A while back. 33 . You’ve learnt how to display a list of recipes by using UITableView. the SDK added a new class called UICollectionView (http:// developer.

Introduction to UICollectionView 2. (We’ll cover this in the next chapter) 34 . is one of the most spectacular API in iOS SDK. You can present items in multicolumn grids. The app presents your photos in grid format. While UITableView manages a collection of data items and displays them on screen in a single-column layout. By default. circular. it even lets developers customize the layout (e. The UICollectionView is composed of several components: • Cells – instances of UICollectionViewCell. In this chapter. you have to write lots of code or make use of third-party libraries in order to build a similar layout. The decoration view is unrelated to the data collection. the SDK comes with a UICollectionViewFlowLayout class that organizes items into a grid with optional header and footer views for each section. cover flow style layout) without changing the data. (We’ll cover this in the next chapter) • Decoration views – think of it as another type of supplementary view but for decoration purpose only. in my opinion. we will build a simple app to display a collection of recipe photos in grid layout. Not only it simplifies the way to arrange visual elements in grid layout. Here are what you’re going to learn: 1. How to Use UICollectionView to build a simple Grid-based layout 3. circular layout. Later. Like UITableViewCell. The cells are the main elements organized by the associated layout. etc. we’ll use the layout class to build the demo app. It’s usually used to implement the header or footer views of sections. a cell represents a single item in the data collection. The UICollectionView. We simply create decoration views to enhance the visual appearance of the collection view. Customizing the Collection Cell Background UICollectionView Basics The UICollectionView operates in a similar way to UITableView. tiled layout. If a UICollectionViewFlowLayout is used.g. Photos app showing photos in grid layout a grid-like format. Before the introduction of UICollectionView. just take a look at the built-in Photos app.If you have no idea about grid-like layout. the UICollectionView class offers developers flexibility to present items using customizable layouts. • Supplementary views – Optional. the cells are arranged in Figure 15-1.

we’ll continue to work on the app and show you how to group the items into different sections. On top of that.C H A P T E R 16 UICOLLECTIONVIEW PART-2 “Design is a funny word. In this chapter. if you dig deeper.” ~ Steve Jobs Previously. As you’ve learnt. But of course.! 35 . every collection view must have a data source object providing it with content to display. Some people think design means how it looks. it's really how it works. while the other section contains recipes for drinks and desserts. It’ll be interesting to spilt recipes into different sections. Let’s say. the RecipePhoto app we developed contains one section only. we covered the basics of UICollectionView and showed you how to present items in grid layout. the first section contains recipes for lunch/dinner. Its responsibility is to provide the collection views with the following: • The number of sections in the collection view • The number of items in each section • The cell view for a particular data item Obviously. you’ll also learn how to add header or footer view to the collection view.

it contains the data items (i. image name of recipe) for that particular section. Figure 1 depicts how we use nested arrays to store the data. the recipeImages array stores the image names for all recipes.Split the Recipe Images into Two Sections In the RecipePhoto app. Originally. Figure 16-1. the RecipeCollectionViewController is the data source object of the collection view. 36 . The top-level array (i. In the RecipeCollectionViewController.m. Let’s go back to the source code. there are a number of changes to be made.(void)viewDidLoad { [super viewDidLoad].e. recipeImages) contains two arrays representing the sections. we’ll modify our code and use nested arrays to store different groups of recipes. The term nested arrays may be new to some of you if you do not have much programming experience. Nested Array The first group contains images of main dish. As we’d like to split the recipes into two groups. change the initialization of “recipeImages” array in the viewDidLoad: method to the following: . For each section array.e. In order to split the recipes into two sections. while the other stores images of drink and dessert.

the collection view works in a way pretty much like table view.” ~ Bruce Lee In the past two chapters. To give you a better idea. but I fear the man who has practiced one kick 10. To provide you with a working example of how the item selection works. When user taps a recipe photo. Users are allowed to select multiple photos and share them on Facebook.C H A P T E R 17 UICOLLECTIONVIEW PART-3 “I fear not the man who has practiced 10. we’ll continue to improve the RecipePhoto app. 2. we’ll cover how to interact with the collection items such as the ways to handle single and multiple item selection. As mentioned before. However.000 times. the app will bring up a modal view and display the photo in larger size. We’ll also implement Facebook sharing in the app in order to show you multiple item selection. You should already know how to display items using UICollectionView. 37 .000 kicks once. we haven’t covered how to interact with the collection view cell. we covered the basics of UICollectionView and header/footer customization. Here are what we’re going to implement: 1.

Handling Single Selection
First, we’ll improve the RecipePhoto app to handle single selection. When user taps any of the recipe photo, the app will bring up a modal view to display the photo in higher resolution.

Designing the User Interface
To begin, let’s design the view controller for displaying the recipe photo. Go to Main.storyboard, drag a View Controller from Object library. Then add an Image View to it and set the width and height to 320 and 200 respectively. Lastly, add a navigation bar to the top of view and assign it with a Bar Button Item. Change the title of the navigation bar to “Photo”. Under the Attribute Inspector, set the identifier of the button item to “Done”. Your View Controller should look similar to the below one:

Figure 17-1. Managing selections in RecipePhoto App


C H A P T E R 18

“The most effective way to do it, is to do it.” ~ Amelia Earhart

Earlier, you’ve learnt how to save data in a plist file. File is one of the ways to save data persistently. In this chapter, we’ll talk about Core Data and how to use it to save persistent information. When building app, sometimes you’d like to save data in a persistent storage such as file or database instead of just holding it in memory. By saving the data to a database, for example, you’ll not lose the data even the app quits or crashes. There are multiple ways to store data in iOS devices. The property file that was covered previously is one of the ways for storing persistent data. However, due to the nature of property file, it is often used to store a small amount of data such as application settings. Database is more suitable to handle large set of data. In this chapter, we’ll see how to use Core Data to manage data in database. The focus of the chapter is to provide a practical introduction of Core Data framework. I expect you’ve already gone through the chapters about Storyboard and UITableView. I will not give in-depth explanation about how to create view controller in storyboard or table view. Refer to the earlier chapters if you haven’t equipped yourself with the knowledge.


Core Data is not a Database
When we talk about persistent data, people probably think of database. If you are familiar with Oracle or MySQL, you know that relational database stores data in the form of table, row and column, and it usually facilitates access through what-so-called SQL query. However, don’t mix up Core Data with database. Though SQLite database is the default persistent store for Core Data on iOS, Core Data is not a relational database. It is actually a framework that lets developers interact with database (or other persistent storage) in an object-oriented way. In other words, you don’t need to use SQL to talk to the database. With Core Data, you can simply map the objects in your apps to the table in the database without even knowing any SQL. As usual, to illustrate the concept, let’s create an iPhone app using Core Data. This app is called RecipeStore. It is very similar to the Recipe app we developed before, but the recipe data will be saved in the database using Core Data. Figure 1 shows a sample screenshot of the app.

Figure 18-1. Recipe App using Core Data


we gave you a brief introduction of Core Data and created a simple app to store recipes in database.C H A P T E R 19 CORE DATA PART-2 “Nothing is impossible. the word itself says 'I'm possible'!” ~ Audrey Hepburn This is the second chapter for our Core Data series. we only showed you how to insert records into database through Core Data Framework and left out the update & delete operations. However. In case you do not want to start from the 41 . we’ll continue to work on the app and focus on the following areas of Core Data: • Updating and deleting a managed object using Core Data • Viewing the raw SQL statement for debugging purpose Updating and Deleting a Managed Object If this is the first time you learn about Core Data. In this chapter. we recommend you to read the previous chapter and build the demo app from scratch. Previously.

if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete object from database [context deleteObject:[recipes objectAtIndex:indexPath. we first grab the manage object context. [self. we also remove the record from the table view.dropboxusercontent. } .(void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { NSManagedObjectContext *context = [self managedObjectContext]. Like creating managed } } I’ll not go into the details about how to remove a row from table view as we’ve gone through it in earlier chapter. NSError *error = nil. [error localizedDescription]).zip to start with. Right after the removal of the object from database. In the last chapter.row]. we already discussed how to fetch and save a managed object using Core Data. 42 . if (![context save:&error]) { NSLog(@"Can't Delete! %@ %@".(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the specified item to be editable. error. return.row]]. To allow user to delete a record from the table view. as you know. Okay.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]. Deleting a managed object is very straightforward. Add the following code to the RecipeStoreTableViewController. return YES. we need to implement the canEditRowAtIndexPath: and commitEditingStyle: methods of the UITableViewDataSource protocol.very beginning. So how can you update or delete an existing managed object from database? Deleting a Managed Object Let’s talk about the delete operation first. However.m: . The context provides the deleteObject: method that allows you to delete the specific object from database. So remember to invoke the method to commit the change. You can simply call up the deleteObject: method of its managed object context and pass the object you want to delete as argument. the deletion will not occur until the save: method is called. let’s continue to develop the demo app. Let’s walk through the code in the commitEditingStyle: method. } // Remove recipe from table view [recipes removeObjectAtIndex:indexPath. you can download this Xcode project from https:// dl.

20 LOCALIZATION In this chapter. The process of adapting an app to support a particular language is usually known as localization. If you just release your app in one language. it may be ignored by user from other parts of the world. Obviously. Chapter image courtesy of woodleywonderworks: http://www. you may want to make your app available in multiple 43 .flickr. The iOS devices including iPhone and iPad are available globally. To deliver a great user experience. iOS users are from different countries and speak different languages. let’s talk about localization.

At the end of the chapter. We’ll localize the app together and make it available in Chinese.Xcode has the built-in support of localization. Translating static or visible text is just part of the localization process. title. 44 . we’ll demonstrate the process by building a simple app and make it available in Chinese. As usual. Localization Overview Figure 20-1. Some people think of localization as the same process of translation. The original app is in English. we’ll show you the step-by-step on how to localize the storyboard file. which will displays the details of a book with a cover image. You’ll also need to handle the different display format of numeric values. you’ll have an app that supports two localizations: English and Chinese. graphics and sound. That’s partially correct. date and time. as well as. images and app name. In this chapter. Localization settings in iOS We are going to create a simple app called “Book Store”. So it’s fairly easy for developer to internationalize an app through the localization feature and some API calls. strings. author and description. Localization involves other elements such as images.

However. So far. we’ll show you how it can done using Storyboard. Static table views are ideal in situations where a pre-defined number 45 . it’s not a must to build a dynamic table view. you may just want to create a static table such as a Settings screen. we’ll build a simple Setting screen. To illustrate how easy you can use Storyboard to implement static table view.21 STATIC TABLE VIEW If you’ve studied the first few chapters. you should have a basic understanding about table view. Xcode provides an easy way to create static table view with minimal code. the table views that we’ve covered are of dynamic content. Sometimes. In this chapter.

On top of that. Figure 22-1 shows a sample screenshot of the RSS Reader app.” ~ Amelia Barr So far everything we have worked on happened locally within an app. When user taps on any of the article. The data are either stored in a file or an array. we’ll go through the concept by building a simple RSS reader app. you’ll learn how to parse XML using NSXMLParser class. we are going to see how to load data from a remote RSS feed. it’ll navigate to load the article in a web view. Of course. It’ll load a RSS feed and display the article items on a table view. In this chapter. 46 . Isn’t it cool? The app that we’re going to build is very simple.C H A P T E R 22 BUILDING A SIMPLE RSS READER APP “It is always the simple that produces the marvelous.

Click Next and save the project. Name the project as RssReader and set the class prefix to the same value.Figure 22-1. 47 . RSS Reader App Creating the Xcode Project Open Xcode and create a new Project using the Single View Application template.

A main view displaying the selected photo from camera roll or the photo just taken 2. The heart and mind are the true lens of the camera.” ~ Yousuf Karsh Previously.C H A P T E R 23 BUILDING A SIMPLE CAMERA APP “Look and think before opening the shutter. In this chapter. The iOS library provides the class UIImagePickerController which is the built-in user interface for managing user interaction with the camera or with the photo library. we covered how to use the built-in APIs to read a RSS feed and build a simple RSS Reader app. To help you understand the usage of UIImagePickerController. the UIImagePickerController requires the use of a delegate to respond to interactions. 48 . As usual. we’ll see how to access the internal photo library and allow user to pick a photo. Also. we are going to learn how to use the built-in camera of the iPhone (or the iPod or iPad. we’ll build a simple camera app. Two buttons: one is used to take a new photo and the other one to select a photo from the photo library. The example application is very simple: 1. if they have one) to take a photo.

Figure 23-1. Name the project as CameraApp and set the class prefix as Camera. Click next and save the project in your folder. 49 . A simple camera app Creating the Xcode Project Launch Xcode and create a new Project using the Single View Application template.

we covered how to create a simple camera app. The iOS API for recording and playing videos can be a little bit confusing for newcomers. The brick walls are there to show us how badly we want things. You can incorporate a movie player’s view into a view owned by your app. or from a remote location. as there are several options available. we’re going to build a similar app but for video recording and playback. you can use the MPMoviePlayerController (http://developer. you have to use the AVFoundation #documentation/MediaPlayer/Reference/MPMoviePlayerController_Class/Reference/ Reference. We’ll keep thing simple and start off by covering the MediaPlayer framework. However. a subview smaller than the full screen).C H A P T E R 24 VIDEO RECORDING AND PLAYBACK “Brick walls are there for a reason. In this chapter.” ~ Randy Pausch Previously. you can use the MediaPlayer framework. If you just want to play a video. playback occurs in a view owned by the movie player. media editing. if you need advanced features such as media asset management. The brick walls aren't there to keep us out. and others. 50 .html). By using MPMoviePlayerController. track management. If you want to display a video immediately and inline (say. which allows us to play a video stored locally in our device. The MediaPlayer framework brings us two main classes to display videos or

Once mpmovieplayerviewcontroller_class/Reference/Reference. If you grasp the basics. you should have no problem utilizing the MPMoviePlayerViewController class. we’ll build a simple demo app to walk you through the concept. The MPMoviePlayerViewController class is designed to present a simple view controller for displaying full-screen movies. the app displays a screen with a single “Capture” button. the video is automatically shown in the main you should use the MPMoviePlayerViewController class (http:// developer. Pretty simple. Simple Video App 51 . In this chapter.On the contrary. we will focus on the MPMoviePlayerController. for example by presenting the video modally. Users are allowed to play back the video inline. if you want to play a full screen video. right? Figure 24-1. Once finished the recording. it’ll bring up the video camera for video recording.html). When you tap the button. Demo App Overview Like any chapter of this book. The demo app (see Figure 24-1) is very simple without fancy user interface. however.

only one application is allowed to run in the foreground. When a notification comes in. 52 . due to the nature of iOS. At that time. iOS displays the notification in the form of on-screen alerts or sounds and it’s up to the user to decide whether to launch the application.0. Way back in iOS 3.25 LOCAL NOTIFICATION Before we dive into the local notification tutorial. let’s first talk about the history. Push notification changes the game by allowing applications to receive updates even it’s not actively running. Apple introduced the Push Notification Service (APNS) to bring the multitasking support to its mobile operating system.

we’ll build a simple To-Do app together. In order to push out such notification. Considered you’re developing a ToDo app. You can schedule a notification with simple API and it’ll be fired up at a proper time. Let’s see how to implement Local Notification and build a simple To-Do app as demo. the app fires up a notification and reminds users about the to-do item.Push notification provides an effective way to support multitasking. The catch is it only works if the device is connected to the Internet. Apple introduced a new type of notification called Local Notification. At a specific time. that’s enough for the history and background. Figure 25-1 Local Notification Demo App 53 . you have to build a server program to talk with APNS and host it somewhere. Since the release of iOS 4. Okay. No more server side programming. No more Internet connection is required. This makes pushing a notification much simpler. The app lets users put in any to-do items and preset a reminder. The To-Do App with Notifications To demonstrate the usage of local notification. And I forgot to mention you have to develop some server programs to interact with APNS. This is too complicated for most developers particularly for those without server side programming experience. the app notifies users about a to-do item at a specific time.

you probably find a series of walkthrough (or tutorial) screens to give you a brief introduction of the features. With page view. There is no single magic bullet. we'll show you how to build a similar type of walk through screens by using UIPageViewController. users can easily navigate between multiple pages through simple gesture. It's a common practice to explain how the app works. In this chapter. 54 . The UIPageViewController class was first introduced in iOS 5 SDK that lets developers build pages of content.C H A P T E R 26 INTRODUCTION TO UIPAGEVIEWCONTROLLER “People are always looking for the single magic bullet that will totally change everything. The page view controller is not limited to create walkthrough screens. where each page is managed by its own view controller. The class was further improved in iOS 6 to support the scrolling transition. You can find examples of page view implementation in games like Angry Birds to show the available levels or book apps to display pages of content.” ~ Temple Grandin For the very first time you launch an app.

the location of the spine . Whenever user taps the "Start again" button to go back to the first page of tutorial. With the basic understanding of the UIPageViewController. We'll just use the scrolling transition style to display a series of walkthrough screens. This type of walkthrough/tutorial screens shouldn't be new to you as they are commonly found in apps such as Snapguide and Airbnb.Figure 26-1. we'll not demonstrate every option of UIPageViewController. Let's get started. Don't worry. the space between pages . A Glance at the Demo App The demo app we are going to create is very simple. However. the transition style – page curl transition style or scrolling transition style 3. It displays 4 pages of screens to give users a brief introduction to the user interface.only applicable to page curl transition style 4.only applicable to scrolling transition style to define the interpage spacing We'll create a simple app together in order to demonstrate how UIPageViewController works. You're allowed to define: 1. the orientation of the page views – vertical or horizontal 2. I believe you should be able to explore other features in the page view controller. Sample Walkthrough Screens from UltraVisual The UIPageViewController is a highly configurable class. User can navigate between pages by swiping through the screen. 55 .

In this chapter.27 SLIDE-OUT SIDEBAR MENU If you read this book from the very beginning and understand the materials thoroughly. If you’re unfamiliar with slide out navigation menu. take a look at figure gave a good explanation and defined it as follows: Slide-out navigation consists of a panel that “slides out” from underneath the left or 56 . And Ken Yarmost (http://kenyarmosh. you’re now ready to move onto something more advanced. we’ll show you how create a slide-out navigation menu similar to the one you find in the Facebook app.

re-build the app and submit to App Store again.C H A P T E R 28 ADDING A CLOUD BACKEND USING PARSE “They don't call it the Internet anymore. I'm no longer resisting the name. Later. Every time when the app launches. For your information.” ~ Larry Ellison In the first few chapters of the book. As the data is saved and loaded remotely. Suppose you’ve published the Recipe app on App Store. they call it cloud computing. you’re free to edit the recipe without rebuilding the app. we built a simple Recipe app together and walk you through the usage of table view. That’s better as it’s a good practice to separate static data from code. what if you need to add more recipes or change some of the recipes? Obviously. it normally takes a week for Apple to review and approve your app. And your users have to upgrade the app before viewing the updated recipes. All the recipe data are stored locally in an array. That’s a lengthy process. both approaches face the same problem. we enhance the app by putting the recipes in a property list file. A common solution is to put the recipe data into a backend database. However. The initial version of Recipe app is very simple. 57 . you’ll need to update the code (or the property file). Call it what you want. it retrieves the data from the backend via web service.

The Recipe app now connects to Parse and download the recipes from the cloud. we’ve migrated the recipes to the Parse backend. you should have a basic idea about the Parse SDK. Let’s get started. By now. In part 1. 58 . So if you haven’t gone through the project and exercise. you’ll learn how to save new recipe to the Parse backend. you’ll learn how to delete the recipe. In the previous chapter. others make it happen. we gave you an introduction of Backend as a Service (BaaS for short) and transformed the Recipe app. it’s highly recommended to check out the first part of the series.C H A P T E R 29 PARSE CLOUD PART-2 “Some people want it to happen. We will build on the Xcode project that you’ve done in Part 1. you’ve learnt how to retrieve objects from Parse. In this part.” ~ Michael Jordan This is the second chapter of the Cloud Backend series. some wish it would happen. as well. Of course. Instead of storing the recipes locally.

Saving data to the Parse cloud Designing the User Interface The main user interface is pretty much unchanged. Previously. However. we’ll add two new features: • Create new recipe and save it to the cloud • Swipe to delete existing recipe from the cloud Figure 29-1.Getting Started Before moving to the coding part. we’ve built a Recipe app to retrieve recipes from Parse and display them using PFQueryTableViewController. In this chapter. let’s have a quick look at the new features. we’ll add a new view controller. in order to let users add new recipe. The “New Recipe” view controller is triggered by 59 .

media listings on iTunes Store. videos. 60 . contacts. Before the debut of iOS 7.30 AIRDROP AirDrop is Apple’s answer to file and data sharing. With AirDrop. URLs. location in Maps. and fifth-generation iPod touch models. Passbook passes. you can easily share data with other nearby iOS devices. In iOS 7. the fourth-generation iPad. Apple introduced a new feature called AirDrop to all iPhone 5 models. In brief. app listings on the App Store. the feature allows you to share photos. the iPad mini. etc. users need to rely on 3rd-party apps such as Bump to share files between iOS devices.

Sign up to vote on this title
UsefulNot useful