Sei sulla pagina 1di 61

PREVIEW VERSION

TABLE OF CONTENTS
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 AppCoda.com 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.

ii

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

SAY HELLO WORLD


I hope you have configured your development environment properly with Xcode installed. If you havent done so, check out the previous chapter about what you need to begin iOS programming. Well use Xcode 5.0 to work on all exercises in this book. You may have heard of Hello World program if you have read any programming book before. It has become the traditional program for first-time learner to create. Its a very simple program that usually outputs Hello, World on the display of a device. In this

chapter, lets follow the programming tradition and create a Hello World app using Xcode. Despite its simplicity, the Hello World program serves a few purposes: It gives you a better idea about the syntax and structure of Objective C, the programming language of iOS. It also gives you a basic introduction of the Xcode environment. Youll learn how to create a Xcode project and create user interface with the built-in interface builder. Youll learn how to compile a program, build the app and test it using the Simulator. Lastly, it makes you think programming is not difficult. I dont want to scare you away.

Take a Look at Your First App


Before we go into the coding part, lets first take a look at our version of the Hello World app. The final deliverable will look like this:

Figure 1-1. Your First iPhone App - Hello World

Its very simple and shows only a Hello World button. When tapped, the app prompts you a message. Thats it. Nothing complex but it helps you kick off your iOS programming journey.

CHAPTER 2

HELLO WORLD APP EXPLAINED


When you learn through coding, [you're] coding to learn. You're learning it in a meaningful context, and that's the best way of learning things. ~ Mitch Resnick

Isnt it easy to build an app? I hope you enjoy reading the first chapter and already created your first iPhone app. Before we continue to build another app, lets step back and have a closer look at the Hello World app. Itll be good for you to understand some of the Objective-C syntax and the inner workings of the app. So far you follow the step-by-step procedures to build the Hello World app. But as you go through the previous chapter, you may come across these questions: What are those .xib, .h and .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 didnt explain any of the above questions. Yet its essential for every developer to understand the inner details behind the code and grasp the basic concept of iOS programming. For some technical concepts, they
6

may be a bit hard to understand particularly you have no programming background. Dont worry, however. This is just a start. As you move on and write more code in later chapters, youll get better understanding about iOS programming. Just try your best to learn as much as possible.

Interface Builder, Header and Implementation Files


First, what are those .xib, .h and .m files? Under the Project Navigator, you should find three main types of files .xib, .h and .m. (If you expand the Supporting Files folder, youll find other file types such as plist and framework. But for now, lets forget about them first. Well talk about them later.) .xib For files with .xib extension, theyre Interface Builder files that store the applications user interface (UI). As you click on the .xib file, Xcode automatically switches to the Interface Builder for you to edit the UI of the app via drag-and-drop.

Figure 2-1. Interface Builder in Xcode

.h and .m Files with .h extension refers to the header files while those with .m extension are the implementation files. Like most of the programming languages, the source code of Objective-C is divided into two parts: interface and implementation. Well, to put in analogy that you can better understand both terms, lets consider a TV remote. Its convenient to control the volume of a TV set wirelessly with a remote. To increase the speaker volume, you press the Volume + button. To switch channel, you simply key in the channel number. Let me ask you. Do you know what happens behind the scene when pressing the Volume button? Probably not. I believe most of us dont know how the remote communicates with the TV set and controls the speaker volume. What we
7

CHAPTER 3

CREATING SIMPLE TABLE


Life is really simple, but we insist on making it complicated. ~ Confucius

Is it fun to create the Hello World app? In this chapter, well work on something more complex and build a simple app using Table View. First, whats a Table View in iPhone app? Table view is one of the common UI elements in iOS apps. Most apps, in some ways, make use of Table View to display list of data. The best example is the built-in Phone app. Your contacts are displayed in a table view. Another example is the Mail app. It uses Table View to display your mail boxes and emails. Not only designed for showing textual data, Table View allows you to present the data in the form of images. The YouTube and Airbnb apps are great examples for the usage.

Figure 3-1. Sample Table View from Snapguide, Digg and Airbnb

Creating a SimpleTable Project


With an idea of table view, lets get our hands dirty and create a simple app. Dont just read the chapter if youre serious about learning iOS programming. Stop reading, open your Xcode and code! This is the best way to study programming. Once launched Xcode, create a new project using the Single View application temple.

CUSTOMIZE TABLE VIEW USING PROTOTYPE CELL


In the last chapter, we created a simple table view app to display a list of recipes with a predefined image. In this chapter, well beautify the table cell and make the app look better. There are a number of changes and enhancement well work on together: 1. Rebuild the same app using prototype cell 2. 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 may wonder why we need to rebuild the same app. There are always more than one way to do things. Previously, we used the table view from Object Library to create the table view. Meanwhile well show you another way to create table view in Xcode. Will it be easier? It may not be easier if you just want to create a simple table. It, however, allows developers to customize a table cell easily.

Building Table View Using Prototype Cell


Since the release of iOS 5, Apple introduced Storyboarding that simplifies the way to design user interfaces for your app. Along with Storyboard, Xcode introduced a new table element called Prototype Cell. You can create table view without using prototype cell, just like what we did earlier. The introduction of prototype cell, however, simplifies the way of creating and designing table cells. You can simply design the cell right inside the Storyboard editor. Well go into the details of cell customization. But first lets see how we use prototype cell to re-create the same Simple Table app. To begin, fire up your Xcode! Once launched Xcode, create a new project using the Single View application template. Name the project as CustomTable and fill in all the required options for the Xcode project, just like you did in the previous chapter.

Figure Figure 4-1. CustomTable Project Options 11

TABLE ROW SELECTION


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

12

Display an alert message when user taps a table cell Display a check mark when user selects a table cell

Easy, right? Lets get started.

Understanding UITableViewDelegate
When we first built the Simple Table View app in Chapter 3, we declared two delegates (UITableViewDelegate, UITableViewDataSource) in the SimpleTableController.h:
#import <UIKit/UIKit.h> @interface SimpleTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> @end

As explained in the earlier chapters, both delegates are known as protocol in Objective-C. You have to conform with the requirements defined in these protocols in order to build a UITableView. Its very common to come across various delegates in iOS programming. Each delegate is responsible for a specific role or task to keep the system simple and clean. Whenever an object needs to perform a certain task, it depends on another object to handle it. This is usually known as separation of concern in software design. When you look at the UITableView class, it also applies this design concept. The two delegates are catered for different purpose. The UITableViewDataSource delegate, that weve learnt, defines methods that are used for displaying table data. On the other hand, the UITableViewDelegate deals with the appearance of the UITableView, as well as, handles the table row selection. Obviously, well make use of the UITableViewDelegate and implement the required methods for handling the selection.

Handling Table Row Selection


Before we change the code, you may wonder: How do we know which methods in UITableViewDelegate need to implement? There are two ways to access the documentation. You can always refer to the Apples official iOS developer reference (https://developer.apple.com/library/ios/) and search for the API
13

TABLE ROW DELETION & MODEL-VIEW-CONTROLLER


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

You cant escape from learning Model-View-Controller (MVC for short) if youre serious about iOS programming. Not limited to iOS programming, MVC is commonly used and quoted in other programming languages such as Java. If you come from other programming backgrounds, MVC shouldnt be new to you.

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

15

Controller controller is the bridge between model and view. It translates the user interaction from the view (e.g. tap) into appropriate action to be performed in the model. For example, user taps a delete button in the view and controller, in turn, triggers a delete operation in the model. After that, it also requests the view to refresh itself to reflect the update of the data model. To help you better understand MVC, lets use our Simple Table app we developed in Chapter 3 as an example. The app displays a list of recipes in the table view. If you turn the concept into visual representation, here is how the table data is displayed:

Figure 6-1. MVC Model Illustrated Using Simple Table as Example

The recipe information that are stored in separate array objects is the Model. Each table row maps to an element of the recipe arrays. The UITableView object is the View that is the interface to be seen by the user. Its responsible for all the visuals (e.g. color of the table rows, font size and type). The TableViewController acts as the bridge between the TableView and Recipe data model. When display table data, UITableView actually asks the Controller for the data to display, that in turn, picks the data from the model.

16

CHAPTER 7

ENHANCE TABLE APP WITH PROPERTY LIST


Talent is cheaper than table salt. What separates the talented individual from the successful one is a lot of hard work. ~ Stephen King

We already built a very simple table app displaying list of recipes. If you look into the app, all our recipes are stored in the source code as arrays. I try to keep the thing simple and focus on showing how to create and customize a UITableView. However, its not a good practice to hard code everything in the code. In real app, we used to externalize these static items (i.e. the recipe information) and put them in a file or database or somewhere else. In iOS programming, there is a file type known as Property List. This kind of file is commonly found in Mac OS and iOS, and is used for storing simple structured data (e.g. application setting). In this chapter, well make some changes in our simple table app and tweak it to use Property List. In brief, here are a couple of things well cover: Convert table data from static array to property list How to read property list

17

Why Externalize the Table Data?


Its always a good practice to separate static data from the code. But why? Whats the advantage to put the table data into an external source? Let me ask you. How do you add 50 more recipes in our custom table app weve built in chapter 4? Probably, youll go back to your code and put all the new recipes in the initialization:
recipeNames = [NSArray arrayWithObjects:@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger", @"Ham and Egg Sandwich", @"Creme Brelee", @"White Chocolate Donut", @"Starbucks Coffee", @"Vegetable Curry", @"Instant Noodle with Egg", @"Noodle with BBQ Pork", @"Japanese Noodle with Pork", @"Green Tea", @"Thai Shrimp Cake", @"Angry Birds Cake", @"Ham and Cheese Panini", nil]; recipeImages = [NSArray arrayWithObjects:@"egg_benedict.jpg", @"mushroom_risotto.jpg", @"full_breakfast.jpg", @"hamburger.jpg", @"ham_and_egg_sandwich.jpg", @"creme_brelee.jpg", @"white_chocolate_donut.jpg", @"starbucks_coffee.jpg", @"vegetable_curry.jpg", @"instant_noodle_with_egg.jpg", @"noodle_with_bbq_pork.jpg", @"japanese_noodle_with_pork.jpg", @"green_tea.jpg", @"thai_shrimp_cake.jpg", @"angry_birds_cake.jpg", @"ham_and_cheese_panini.jpg", nil]; recipePrepTimes = [NSArray arrayWithObjects:@"30 min", @"30 min", @"20 min", @"30 min", @"10 min", @"1 hour", @"45 min", @"5 min", @"30 min", @"8 min", @"20 min", @"20 min", @"5 min", @"1.5 hour", @"4 hours", @"10 min", nil];

There is nothing wrong doing this. But look at the code! Its not easy to edit and you have to strictly follow the Objective C syntax. Changing the code may accidentally introduce other errors. Thats not we want. Apparently, it would be better to separate the data and the programming logic (i.e. the code). Does it look better when the table data is stored like this?

18

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

Its Launch Image, Not Splash Screen


First thing first, for those who are new to programming and havent heard of the term Splash Screen, let me first give a brief explanation about it. Splash screen is commonly found in desktop applications to display branding information. This is the first screen you see when launching an application. Usually, splash screen is an image covering the entire screen and disappears after the main screen is loaded. In iOS, however, it doesnt use the term Splash Screen. This kind of startup screen is commonly known as Launch Image. Below figure shows you a few samples of launch image:!

Figure 8-1. Sample Launch Images

Unlike splash screen, youre not encouraged to use launch image for branding purpose, though some apps make use of it to display their logos. According to Apple, 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. Launch image is especially important for apps that take longer time to launch. Perceptually, it gives a better user experience. As an example, figure 2 shows the launch image of Yahoos Weather app.

20

CHAPTER 9

NAVIGATION CONTROLLER
If you hear a voice within you say 'you cannot paint,' then by all means paint, and that voice will be silenced ~ Vincent Van Gogh

In this chapter, well show you how to use Storyboards to build a Navigation interface and integrate it with table view. We try to keep thing simple and focus on explaining the concept. In chapter 5, weve created a demo app that handles table row selection. Well use that project as foundation and build upon it. Dont expect any fancy interface or pretty graphic. Well keep tweaking the artwork in later chapters.

Whats Navigation Controller?


First thing first, whats navigation controller? Like table view, navigation controller is another UI element you commonly find in iOS app. It provides a drill-down interface for hierarchical content. Take a look at the built-in Photos app, YouTube, and Contacts. Theyre all built using navigation controller to display hierarchical content. Usually table view and navigation controller work hand in hand for most of the apps. That said, this doesnt mean you have to use both together.

21

Figure 9-1. An example of Navigation Controller - Photos App

Scene and Segue in Storyboard


Weve built most of the apps by using Storyboard. But so far we just layout one view controller in the storyboard for building table view app. Storyboard allows you to do more than that. 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.

Figure 9-2. Storyboard - Scene and Segue 22

C H A P T E R 10

PASSING DATA BETWEEN VIEW CONTROLLERS


Sometimes when you sacrifice something precious, you're not really losing it. You're just passing it on to someone else. ~ Mitch Albom

Previously, we built a simple Recipe app with navigation interface. As I said before, we left one thing that was not discussed: data passing between scenes (i.e. view controllers) with segue. First, lets take a quick look at what weve accomplished. So far, 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, we havent implemented the detail view which just shows a static label. In this chapter, well continue to work on this project and polish the app.

Creating a View Controller Class


In the previous chapter, we created a view controller that serves as the detail view controller of a recipe in the storyboard editor. The view controller is assigned with the UIViewController class by default.
23

Figure 10-1. Default View Controller - UIViewController

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

24

C H A P T E R 11

TAB BAR CONTROLLER AND WEB VIEW


Anyone who stops learning is old, whether at twenty or eighty. Anyone who keeps learning stays young. The greatest thing in life is to keep your mind young. ~ Henry Ford

Last time, we discussed how to pass data between view controllers with segue. It should be easy, right? In this chapter, well continue to polish our Recipe app and see how you can make use of two other common UI elements in iOS apps. Here are what youre 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, lets first have a brief introduction for Tab Bar Controller and UIWebView. You may not be familiar with the term Tab Bar but you should come across it in most of the iOS apps. Just take a look at figure 1 that shows a few sample apps including Twitter, TED, iTunes and TheVerge. All of them make use of the tab bar controller to display distinct view in each tab. Normally the tab bar contains at least two tabs and youre allowed to add up to five tabs depending on your needs.

25

Figure 11-1. Sample Apps with Tab Bar Interface

UIWebView, on the other hand, is a handy component to load web content. In some cases, you want to display a single web page locally in your app or let users access external web pages within your app. You can simply embed the UIWebView object in your app and send it a HTTP request to load the web content.

Creating a Tab Bar Controller


Okay, lets back to our Xcode project. Let me first recap what weve done. If youve followed the previous chapter, you should build a simple recipe app with navigation interface. Its not fully implemented but just works.

26

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. ~ Linus Torvalds

If you read from the very beginning of the book and have worked through all the projects, youve gone pretty far. By now, you should be able to build an iPhone app with tab bar, navigation controller and table view using Storyboard. Well further enhance the detail view of the Recipe app as the original detail view was way too plain. How can we display more information including the recipe image in the detail view? This shouldnt be difficult if you understand the materials and I intentionally left out that part for you at the time I wrote the chapter. Did you manage to create your own detail view for the Recipe app? Anyway, well revisit it and show you how to improve the detail screen. But before that, I have to introduce you the basics of Object Oriented Programming. In the next chapter, well build on top of what well learn in this chapter and enhance the detail view screen. Dont be scared by the term Object Oriented Programming or OOP in short. Its not a new kind of programming language but a programming concept/technique. While some programming books start out by introducing the OOP concept, I intentionally left it out when I first began writing the book. I want to keep thing simple and show you (even
27

without any programming background) how to create an app. I dont want to scare you away from building apps, just because of a technical term. However, I think its time to cover the concept. If youre still around reading this chapter, I believe youre determined to learn iOS programming and you want to take programming skills to the next level.! ! Okay, lets get started.

Object Oriented Programming Some Theory


Objective-C is known as an Object Oriented Programming (OOP) language. OOP is a way of constructing software application composed of objects. In other words, most of the code youve written in the app in some ways deal with objects of some kind. UIViewController, UIButton, UINavigationController and UITableView are some of the objects come with the iOS SDK. Not only youve used the built-in objects in your iOS app, youve created some objects of your own such as RecipeDetailViewController and SimpleTableCell. 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. Here, the smaller pieces are the objects. Each object has its own responsibility and objects coordinate with each other in order to make the software work. Thats the basic concept of OOP. Take the Hello World app that weve built at the very beginning as an example. The UIViewController object is responsible for the view of the app and as a placeholder for the Hello World button. The UIButton (i.e. Hello World button) object is responsible to display a standard iOS button on screen and listen to any touch events. The UIAlertView object, on the other hand, is responsible to display the alert message to user. Most importantly, all these objects work together to create the Hello World app.

28

C H A P T E R 13

BEAUTIFY THE RECIPE APP


Beautiful things don't ask for attention. ~ James Thurber

We already showed you how to use segue in storyboard to pass data between different view controllers. Youve built a simple Recipe app to display a list of recipes. When user taps on any of the recipes, the app navigates to a detailed view and brings up the recipe name. This is very simple app. But if you understand how it works, this is the foundation to help you advance into a full-fledge iOS developer. Wouldnt be great if we further improve the detail view of the app? The original detail view is primitive with the recipe name only. How can we improve it and display more information such as the preparation time, ingredient and the dish photo? In this chapter, well work on it together and make the app even better. Before we move on, however, make sure you check out the chapter about Object Oriented Programming. You have to understand the basics of OOP before you can work on the project. If you havent done so, take some time and read through the chapter. You cant become a fullfledged iOS developer without learning objects and classes.

29

The Final Deliverable


To give you an idea about the improvement, lets first take a look at the final deliverable. As you can see from figure 1, the revamped Recipe app shows detailed information about a recipe with a better look & feel.

Figure 13-1. Recipe app with improved detail view

Not only with improved user interface, the app gives user more information about a recipe including a list of ingredients, preparation time and a large photo of the recipe.

Adding Ingredients to the Recipe Data


With the additional property of ingredients, apparently, we have to update our code to due with it. First, add a new property named ingredients in the Recipe.h:
@property (nonatomic, strong) NSArray *ingredients;

In the viewDidLoad method of RecipeTableViewController.m, we initialize the Recipe objects with additional ingredients data:

- (void)viewDidLoad {

30

14

ADDING SEARCH BAR


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

Figure 14-1. Enhancing recipe app with a search bar

Understanding Search Display Controller


You can use search display controller (i.e. UISearchDisplayController class) to manage search in your app. A search display controller manages display of a search bar and a table view that displays the results of a search of data. When a user starts a search, the search display controller will superimpose the search interface over the original view and display the search results. Interestingly, the results are displayed in a table view thats created by the search display controller.

32

15

GRID LAYOUT USING UICOLLECTIONVIEW


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

33

If you have no idea about grid-like layout, just take a look at the built-in Photos app. The app presents your photos in grid format. Before the introduction of UICollectionView, you have to write lots of code or make use of third-party libraries in order to build a similar layout. The UICollectionView, in my opinion, is one of the most spectacular API in iOS SDK. Not only it simplifies the way to arrange visual elements in grid layout, it even lets developers customize the layout (e.g. circular, cover flow style layout) without changing the data. In this chapter, we will build a simple app to display a collection of recipe photos in grid layout. Here are what youre going to learn: 1. Introduction to UICollectionView 2. How to Use UICollectionView to build a simple Grid-based layout 3. Customizing the Collection Cell Background

UICollectionView Basics
The UICollectionView operates in a similar way to UITableView. While UITableView manages a collection of data items and displays them on screen in a single-column layout, the UICollectionView class offers developers flexibility to present items using customizable layouts. You can present items in multicolumn grids, tiled layout, circular layout, etc. By default, the SDK comes with a UICollectionViewFlowLayout class that organizes items into a grid with optional header and footer views for each section. Later, well use the layout class to build the demo app. The UICollectionView is composed of several components: Cells instances of UICollectionViewCell. Like UITableViewCell, a cell represents a single item in the data collection. The cells are the main elements organized by the associated layout. If a UICollectionViewFlowLayout is used, the cells are arranged in Figure 15-1. Photos app showing photos in grid layout a grid-like format. Supplementary views Optional. Its usually used to implement the header or footer views of sections. (Well cover this in the next chapter) Decoration views think of it as another type of supplementary view but for decoration purpose only. The decoration view is unrelated to the data collection. We simply create decoration views to enhance the visual appearance of the collection view. (Well cover this in the next chapter)
34

C H A P T E R 16

UICOLLECTIONVIEW PART-2
Design is a funny word. Some people think design means how it looks. But of course, if you dig deeper, it's really how it works. ~ Steve Jobs

Previously, we covered the basics of UICollectionView and showed you how to present items in grid layout. Itll be interesting to spilt recipes into different sections. Lets say, the first section contains recipes for lunch/dinner, while the other section contains recipes for drinks and desserts. As youve learnt, every collection view must have a data source object providing it with content to display. 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, the RecipePhoto app we developed contains one section only. In this chapter, well continue to work on the app and show you how to group the items into different sections. On top of that, youll also learn how to add header or footer view to the collection view.!

35

Split the Recipe Images into Two Sections


In the RecipePhoto app, the RecipeCollectionViewController is the data source object of the collection view. In order to split the recipes into two sections, there are a number of changes to be made. Originally, the recipeImages array stores the image names for all recipes. As wed like to split the recipes into two groups, well 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. Figure 1 depicts how we use nested arrays to store the data.

Figure 16-1. Nested Array

The first group contains images of main dish, while the other stores images of drink and dessert. The top-level array (i.e. recipeImages) contains two arrays representing the sections. For each section array, it contains the data items (i.e. image name of recipe) for that particular section. Lets go back to the source code. In the RecipeCollectionViewController.m, change the initialization of recipeImages array in the viewDidLoad: method to the following:
- (void)viewDidLoad { [super viewDidLoad];

36

C H A P T E R 17

UICOLLECTIONVIEW PART-3
I fear not the man who has practiced 10,000 kicks once, but I fear the man who has practiced one kick 10,000 times. ~ Bruce Lee

In the past two chapters, we covered the basics of UICollectionView and header/footer customization. You should already know how to display items using UICollectionView. However, we havent covered how to interact with the collection view cell. As mentioned before, the collection view works in a way pretty much like table view. To give you a better idea, well cover how to interact with the collection items such as the ways to handle single and multiple item selection. To provide you with a working example of how the item selection works, well continue to improve the RecipePhoto app. Here are what were going to implement: 1. When user taps a recipe photo, the app will bring up a modal view and display the photo in larger size. 2. Well also implement Facebook sharing in the app in order to show you multiple item selection. Users are allowed to select multiple photos and share them on Facebook.

37

Handling Single Selection


First, well 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, lets 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

38

C H A P T E R 18

INTRODUCTION TO CORE DATA


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

Earlier, youve learnt how to save data in a plist file. File is one of the ways to save data persistently. In this chapter, well talk about Core Data and how to use it to save persistent information. When building app, sometimes youd 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, youll 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, well 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 youve 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 havent equipped yourself with the knowledge.

39

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, dont 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 dont 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, lets 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

40

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. Previously, we gave you a brief introduction of Core Data and created a simple app to store recipes in database. However, we only showed you how to insert records into database through Core Data Framework and left out the update & delete operations. In this chapter, well 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, we recommend you to read the previous chapter and build the demo app from scratch. In case you do not want to start from the

41

very beginning, you can download this Xcode project from https:// dl.dropboxusercontent.com/u/2857188/RecipeStore.zip to start with. In the last chapter, we already discussed how to fetch and save a managed object using Core Data. So how can you update or delete an existing managed object from database?

Deleting a Managed Object


Lets talk about the delete operation first. Deleting a managed object is very straightforward. You can simply call up the deleteObject: method of its managed object context and pass the object you want to delete as argument. Okay, lets continue to develop the demo app. To allow user to delete a record from the table view, as you know, we need to implement the canEditRowAtIndexPath: and commitEditingStyle: methods of the UITableViewDataSource protocol. Add the following code to the RecipeStoreTableViewController.m:
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the specified item to be editable. return YES; } - (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { NSManagedObjectContext *context = [self managedObjectContext]; if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete object from database [context deleteObject:[recipes objectAtIndex:indexPath.row]]; NSError *error = nil; if (![context save:&error]) { NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]); return; } // Remove recipe from table view [recipes removeObjectAtIndex:indexPath.row]; [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; } }

Ill not go into the details about how to remove a row from table view as weve gone through it in earlier chapter. Lets walk through the code in the commitEditingStyle: method. Like creating managed object, we first grab the manage object context. The context provides the deleteObject: method that allows you to delete the specific object from database. However, the deletion will not occur until the save: method is called. So remember to invoke the method to commit the change. Right after the removal of the object from database, we also remove the record from the table view.
42

20

LOCALIZATION
In this chapter, lets talk about localization. The iOS devices including iPhone and iPad are available globally. Obviously, iOS users are from different countries and speak different languages. If you just release your app in one language, it may be ignored by user from other parts of the world. To deliver a great user experience, you may want to make your app available in multiple languages. The process of adapting an app to support a particular language is usually known as localization.

Chapter image courtesy of woodleywonderworks: http://www.ickr.com/photos/wwworks/4759535950/in/photostream/

43

Xcode has the built-in support of localization. So its fairly easy for developer to internationalize an app through the localization feature and some API calls. Some people think of localization as the same process of translation. Thats partially correct. Translating static or visible text is just part of the localization process. Localization involves other elements such as images, graphics and sound. Youll also need to handle the different display format of numeric values, as well as, date and time. In this chapter, well show you the step-by-step on how to localize the storyboard file, strings, images and app name. As usual, well demonstrate the process by building a simple app and make it available in Chinese.

Localization Overview

Figure 20-1. Localization settings in iOS

We are going to create a simple app called Book Store, which will displays the details of a book with a cover image, title, author and description. The original app is in English. Well localize the app together and make it available in Chinese. At the end of the chapter, youll have an app that supports two localizations: English and Chinese.

44

21

STATIC TABLE VIEW


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

C H A P T E R 22

BUILDING A SIMPLE RSS READER APP


It is always the simple that produces the marvelous. ~ Amelia Barr

So far everything we have worked on happened locally within an app. The data are either stored in a file or an array. In this chapter, we are going to see how to load data from a remote RSS feed. On top of that, youll learn how to parse XML using NSXMLParser class. Of course, well go through the concept by building a simple RSS reader app. Isnt it cool? The app that were going to build is very simple. Itll load a RSS feed and display the article items on a table view. When user taps on any of the article, itll navigate to load the article in a web view. Figure 22-1 shows a sample screenshot of the RSS Reader app.

46

Figure 22-1. RSS Reader App

Creating the Xcode Project


Open Xcode and create a new Project using the Single View Application template. Name the project as RssReader and set the class prefix to the same value. Click Next and save the project.

47

C H A P T E R 23

BUILDING A SIMPLE CAMERA APP


Look and think before opening the shutter. The heart and mind are the true lens of the camera. ~ Yousuf Karsh

Previously, we covered how to use the built-in APIs to read a RSS feed and build a simple RSS Reader app. In this chapter, we are going to learn how to use the built-in camera of the iPhone (or the iPod or iPad, if they have one) to take a photo. Also, well see how to access the internal photo library and allow user to pick a photo. 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. As usual, the UIImagePickerController requires the use of a delegate to respond to interactions. To help you understand the usage of UIImagePickerController, well build a simple camera app. The example application is very simple: 1. A main view displaying the selected photo from camera roll or the photo just taken 2. Two buttons: one is used to take a new photo and the other one to select a photo from the photo library.

48

Figure 23-1. A simple camera app

Creating the Xcode Project


Launch Xcode and create a new Project using the Single View Application template. Name the project as CameraApp and set the class prefix as Camera. Click next and save the project in your folder.

49

C H A P T E R 24

VIDEO RECORDING AND PLAYBACK


Brick walls are there for a reason. The brick walls aren't there to keep us out. The brick walls are there to show us how badly we want things. ~ Randy Pausch

Previously, we covered how to create a simple camera app. In this chapter, were going to build a similar app but for video recording and playback. The iOS API for recording and playing videos can be a little bit confusing for newcomers, as there are several options available. If you just want to play a video, you can use the MediaPlayer framework, which allows us to play a video stored locally in our device, or from a remote location. However, if you need advanced features such as media asset management, media editing, track management, and others, you have to use the AVFoundation framework. Well keep thing simple and start off by covering the MediaPlayer framework. The MediaPlayer framework brings us two main classes to display videos or movies. If you want to display a video immediately and inline (say, a subview smaller than the full screen), you can use the MPMoviePlayerController (http://developer.apple.com/library/ios/ #documentation/MediaPlayer/Reference/MPMoviePlayerController_Class/Reference/ Reference.html). By using MPMoviePlayerController, playback occurs in a view owned by the movie player. You can incorporate a movie players view into a view owned by your app.
50

On the contrary, if you want to play a full screen video, for example by presenting the video modally, you should use the MPMoviePlayerViewController class (http:// developer.apple.com/library/ios/#documentation/mediaplayer/reference/ mpmovieplayerviewcontroller_class/Reference/Reference.html). The MPMoviePlayerViewController class is designed to present a simple view controller for displaying full-screen movies. In this chapter, we will focus on the MPMoviePlayerController. If you grasp the basics, however, you should have no problem utilizing the MPMoviePlayerViewController class.

Demo App Overview


Like any chapter of this book, well build a simple demo app to walk you through the concept. The demo app (see Figure 24-1) is very simple without fancy user interface. Once opened, the app displays a screen with a single Capture button. When you tap the button, itll bring up the video camera for video recording. Once finished the recording, the video is automatically shown in the main screen. Users are allowed to play back the video inline. Pretty simple, right?

Figure 24-1. Simple Video App

51

25

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

Push notification provides an effective way to support multitasking. The catch is it only works if the device is connected to the Internet. And I forgot to mention you have to develop some server programs to interact with APNS. Considered youre developing a ToDo app, the app notifies users about a to-do item at a specific time. In order to push out such notification, you have to build a server program to talk with APNS and host it somewhere. This is too complicated for most developers particularly for those without server side programming experience. Since the release of iOS 4, Apple introduced a new type of notification called Local Notification. This makes pushing a notification much simpler. No more server side programming. No more Internet connection is required. You can schedule a notification with simple API and itll be fired up at a proper time. Okay, thats enough for the history and background. Lets see how to implement Local Notification and build a simple To-Do app as demo.

The To-Do App with Notifications


To demonstrate the usage of local notification, well build a simple To-Do app together. The app lets users put in any to-do items and preset a reminder. At a specific time, the app fires up a notification and reminds users about the to-do item.

Figure 25-1 Local Notification Demo App

53

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. There is no single magic bullet. ~ Temple Grandin

For the very first time you launch an app, you probably find a series of walkthrough (or tutorial) screens to give you a brief introduction of the features. It's a common practice to explain how the app works. In this chapter, we'll show you how to build a similar type of walk through screens by using UIPageViewController. The UIPageViewController class was first introduced in iOS 5 SDK that lets developers build pages of content, where each page is managed by its own view controller. The class was further improved in iOS 6 to support the scrolling transition. With page view, users can easily navigate between multiple pages through simple gesture. The page view controller is not limited to create walkthrough screens. 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.

54

Figure 26-1. Sample Walkthrough Screens from UltraVisual

The UIPageViewController is a highly configurable class. You're allowed to define: 1. the orientation of the page views vertical or horizontal 2. the transition style page curl transition style or scrolling transition style 3. the location of the spine - only applicable to page curl transition style 4. the space between pages - 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. However, we'll not demonstrate every option of UIPageViewController. We'll just use the scrolling transition style to display a series of walkthrough screens. Don't worry. With the basic understanding of the UIPageViewController, I believe you should be able to explore other features in the page view controller. Let's get started.

A Glance at the Demo App


The demo app we are going to create is very simple. It displays 4 pages of screens to give users a brief introduction to the user interface. User can navigate between pages by swiping through the screen. Whenever user taps the "Start again" button to go back to the first page of tutorial. This type of walkthrough/tutorial screens shouldn't be new to you as they are commonly found in apps such as Snapguide and Airbnb.

55

27

SLIDE-OUT SIDEBAR MENU


If you read this book from the very beginning and understand the materials thoroughly, youre now ready to move onto something more advanced. In this chapter, well show you how create a slide-out navigation menu similar to the one you find in the Facebook app. If youre unfamiliar with slide out navigation menu, take a look at figure 27-1. And Ken Yarmost (http://kenyarmosh.com/ios-pattern-slide-out-navigation/) 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

C H A P T E R 28

ADDING A CLOUD BACKEND USING PARSE


They don't call it the Internet anymore, they call it cloud computing. I'm no longer resisting the name. Call it what you want. ~ Larry Ellison

In the first few chapters of the book, we built a simple Recipe app together and walk you through the usage of table view. The initial version of Recipe app is very simple. All the recipe data are stored locally in an array. Later, we enhance the app by putting the recipes in a property list file. Thats better as its a good practice to separate static data from code. However, both approaches face the same problem. Suppose youve published the Recipe app on App Store, what if you need to add more recipes or change some of the recipes? Obviously, youll need to update the code (or the property file), re-build the app and submit to App Store again. And your users have to upgrade the app before viewing the updated recipes. Thats a lengthy process. For your information, it normally takes a week for Apple to review and approve your app. A common solution is to put the recipe data into a backend database. Every time when the app launches, it retrieves the data from the backend via web service. As the data is saved and loaded remotely, youre free to edit the recipe without rebuilding the app.

57

C H A P T E R 29

PARSE CLOUD PART-2


Some people want it to happen, some wish it would happen, others make it happen. ~ Michael Jordan

This is the second chapter of the Cloud Backend series. In the previous chapter, we gave you an introduction of Backend as a Service (BaaS for short) and transformed the Recipe app. Instead of storing the recipes locally, weve migrated the recipes to the Parse backend. The Recipe app now connects to Parse and download the recipes from the cloud. By now, you should have a basic idea about the Parse SDK. In part 1, youve learnt how to retrieve objects from Parse. In this part, youll learn how to save new recipe to the Parse backend. Of course, youll learn how to delete the recipe, as well. We will build on the Xcode project that youve done in Part 1. So if you havent gone through the project and exercise, its highly recommended to check out the first part of the series. Lets get started.

58

Getting Started
Before moving to the coding part, lets have a quick look at the new features. Previously, weve built a Recipe app to retrieve recipes from Parse and display them using PFQueryTableViewController. In this chapter, well add two new features: Create new recipe and save it to the cloud Swipe to delete existing recipe from the cloud

Figure 29-1. Saving data to the Parse cloud

Designing the User Interface


The main user interface is pretty much unchanged. However, in order to let users add new recipe, well add a new view controller. The New Recipe view controller is triggered by

59

30

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

60

Potrebbero piacerti anche