learn ios7 programming preview

61
PREVIEW VERSION

Upload: victor-v-evans

Post on 20-Jan-2016

495 views

Category:

Documents


0 download

DESCRIPTION

ios 7 programming

TRANSCRIPT

Page 1: Learn Ios7 Programming Preview

PREVIEW VERSION

Page 2: Learn Ios7 Programming Preview

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

TABLE OF CONTENTS

i

Page 3: Learn Ios7 Programming Preview

Copyright © 2014 AppCoda.comAll 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

Page 4: Learn Ios7 Programming Preview

In September 2011, I released my first iPhone app on the App Store. It’s 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 can’t 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. 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. 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, it’s 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. It’s similar to learning a foreign language. You can’t just read a book and teach yourself Japanese (or other languages). You have to practice, practice and practice. That’s 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 you’re planning to read this book in bed and expect to understand app development, however, this book is not for you. It’s a book for those who take actions. You’ll get a lot of hands-on exercises and projects. You’ll 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 you’ll master the fundamentals of iOS 7 programming along the way.

Thanks for picking up this book. I hope you’ll enjoy reading it and that you’ll soon put up your first iOS app on App Store. If you’d like to share with me about your first app, drop me email at [email protected]. I love to hear from you.

Simon NgFounder of appcoda.com

PREFACE

iii

Page 5: Learn Ios7 Programming Preview

I hope you have configured your development environment properly with Xcode installed. If you haven’t done so, check out the previous chapter about what you need to begin iOS programming. We’ll 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. It’s a very simple program that usually outputs “Hello, World” on the display of a device. In this

SAY HELLO WORLD

1

4

Page 6: Learn Ios7 Programming Preview

chapter, let’s 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. You’ll learn how to create a Xcode project and create user interface with the built-in interface builder.

• You’ll 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 don’t want to scare you away.

Take a Look at Your First AppBefore we go into the coding part, let’s 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

It’s very simple and shows only a “Hello World” button. When tapped, the app prompts you a message. That’s it. Nothing complex but it helps you kick off your iOS programming journey.

5

Page 7: Learn Ios7 Programming Preview

Isn’t 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, let’s step back and have a closer look at the Hello World app. It’ll 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 didn’t explain any of the above questions. Yet it’s 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

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

CHAPTER 2

6

Page 8: Learn Ios7 Programming Preview

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

Interface Builder, Header and Implementation FilesFirst, 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, you’ll find other file types such as plist and framework. But for now, let’s forget about them first. We’ll talk about them later.)

.xib – For files with .xib extension, they’re Interface Builder files that store the application’s 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, let’s consider a TV remote. It’s 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 don’t know how the remote communicates with the TV set and controls the speaker volume. What we

7

Page 9: Learn Ios7 Programming Preview

Is it fun to create the Hello World app? In this chapter, we’ll work on something more complex and build a simple app using Table View.

First, what’s 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.

CREATING SIMPLE TABLE

“Life is really simple, but we insist on making it complicated.”

~ Confucius

CHAPTER 3

8

Page 10: Learn Ios7 Programming Preview

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

Creating a SimpleTable ProjectWith an idea of table view, 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. 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.

9

Page 11: Learn Ios7 Programming Preview

In the last chapter, we created a simple table view app to display a list of recipes with a pre-defined image. In this chapter, we’ll beautify the table cell and make the app look better. There are a number of changes and enhancement we’ll work on together:

1. Rebuild the same app using prototype cell2. Display individual image for each recipe instead of showing the same thumbnail for all

recipes3. Custom the table view instead of using the default style of table view cell

CUSTOMIZE TABLE VIEW USING PROTOTYPE CELL

4

10

Page 12: Learn Ios7 Programming Preview

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 we’ll 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 CellSince 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.

We’ll go into the details of cell customization. But first let’s 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

Page 13: Learn Ios7 Programming Preview

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 we’ll go through in this chapter and see how you can handle cell selection.

We’ll build on the CustomTable app that we’ve worked on in the previous chapter. And we’ll add a couple of enhancements:

TABLE ROW SELECTION

5

12

Page 14: Learn Ios7 Programming Preview

• Display an alert message when user taps a table cell

• Display a check mark when user selects a table cell

Easy, right? Let’s get started.

Understanding UITableViewDelegateWhen 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.

It’s 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 we’ve 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, we’ll make use of the UITableViewDelegate and implement the required methods for handling the selection.

Handling Table Row SelectionBefore 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 Apple’s official iOS developer reference (https://developer.apple.com/library/ios/) and search for the API

13

Page 15: Learn Ios7 Programming Preview

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, it’s 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.

TABLE ROW DELETION & MODEL-VIEW-CONTROLLER

6

14

Page 16: Learn Ios7 Programming Preview

You can’t escape from learning Model-View-Controller (MVC for short) if you’re 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 shouldn’t 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 Fowlerhttp://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

Page 17: Learn Ios7 Programming Preview

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, let’s 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. It’s 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

Page 18: Learn Ios7 Programming Preview

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, it’s 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, we’ll make some changes in our simple table app and tweak it to use Property List.

In brief, here are a couple of things we’ll cover:

• Convert table data from static array to property list

• How to read property list

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

CHAPTER 7

17

Page 19: Learn Ios7 Programming Preview

Why Externalize the Table Data?It’s always a good practice to separate static data from the code. But why? What’s 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 we’ve built in chapter 4? Probably, you’ll 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! It’s not easy to edit and you have to strictly follow the Objective C syntax. Changing the code may accidentally introduce other errors. That’s 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

Page 20: Learn Ios7 Programming Preview

Before moving onto another detailed chapter about Navigation Controller, I’d 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.

LAUNCH IMAGE

8

19

Page 21: Learn Ios7 Programming Preview

It’s Launch Image, Not Splash ScreenFirst thing first, for those who are new to programming and haven’t 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 doesn’t 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, you’re 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 Yahoo’s Weather app.

20

Page 22: Learn Ios7 Programming Preview

In this chapter, we’ll 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, we’ve created a demo app that handles table row selection. We’ll use that project as foundation and build upon it. Don’t expect any fancy interface or pretty graphic. We’ll keep tweaking the artwork in later chapters.

What’s Navigation Controller?First thing first, what’s 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. They’re 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 doesn’t mean you have to use both together.

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

CHAPTER 9

21

Page 23: Learn Ios7 Programming Preview

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

Scene and Segue in StoryboardWe’ve 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

Page 24: Learn Ios7 Programming Preview

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, let’s take a quick look at what we’ve 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 haven’t implemented the detail view which just shows a static label. In this chapter, we’ll continue to work on this project and polish the app.

Creating a View Controller ClassIn 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.

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

CHAPTER 10

23

Page 25: Learn Ios7 Programming Preview

Figure 10-1. Default View Controller - UIViewController

Let’s 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 it’s a subclass of “UIViewController”. Make sure you uncheck the option of “With XIB for user interface”. As we’re 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

Page 26: Learn Ios7 Programming Preview

Last time, we discussed how to pass data between view controllers with segue. It should be easy, right? In this chapter, we’ll 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 you’re going to learn:

• How to Create a Tab Bar Controller

• How to Create an About page using UIWebView

Tab Bar Controller and UIWebViewAs usual, let’s 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 you’re allowed to add up to five tabs depending on your needs.

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

CHAPTER 11

25

Page 27: Learn Ios7 Programming Preview

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 ControllerOkay, let’s back to our Xcode project. Let me first recap what we’ve done. If you’ve followed the previous chapter, you should build a simple recipe app with navigation interface. It’s not fully implemented but just works.

26

Page 28: Learn Ios7 Programming Preview

If you read from the very beginning of the book and have worked through all the projects, you’ve gone pretty far. By now, you should be able to build an iPhone app with tab bar, navigation controller and table view using Storyboard. We’ll 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 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.

Did you manage to create your own detail view for the Recipe app? Anyway, we’ll 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, we’ll build on top of what we’ll learn in this chapter and enhance the detail view screen.

Don’t be scared by the term “Object Oriented Programming” or OOP in short. It’s 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

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

CHAPTER 12

27

Page 29: Learn Ios7 Programming Preview

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

Object Oriented Programming – Some TheoryObjective-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 you’ve 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 you’ve used the built-in objects in your iOS app, you’ve 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. That’s the basic concept of OOP.

Take the Hello World app that we’ve 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

Page 30: Learn Ios7 Programming Preview

We already showed you how to use segue in storyboard to pass data between different view controllers. You’ve 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.

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. How can we improve it and display more information such as the preparation time, ingredient and the dish photo? In this chapter, we’ll 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 haven’t done so, take some time and read through the chapter. You can’t become a full-fledged iOS developer without learning objects and classes.

BEAUTIFY THE RECIPE APP

“Beautiful things don't ask for attention.”

~ James Thurber

CHAPTER 13

29

Page 31: Learn Ios7 Programming Preview

The Final DeliverableTo give you an idea about the improvement, let’s 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 DataWith 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

Page 32: Learn Ios7 Programming Preview

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, we’ll enhance the recipe app to let users search through the recipe list by specifying a search term.

Well, it’s not difficult to add a search bar but it takes a little bit of extra work. We’ll continue to work on the Xcode project we developed in previous chapter. If you haven’t gone through the chapter, go back and take some time to check it out.

ADDING SEARCH BAR

14

31

Page 33: Learn Ios7 Programming Preview

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

Understanding Search Display ControllerYou 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 that’s created by the search display controller.

32

Page 34: Learn Ios7 Programming Preview

A while back, we built a Recipe app. You’ve learnt how to display a list of recipes by using UITableView. Wouldn’t 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 grid-like layout out of the box.

GRID LAYOUT USING UICOLLECTIONVIEW

15

33

Page 35: Learn Ios7 Programming Preview

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 you’re going to learn:

1. Introduction to UICollectionView2. How to Use UICollectionView to build a simple Grid-based layout3. Customizing the Collection Cell Background

UICollectionView BasicsThe 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 multi-column 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, we’ll 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 a grid-like format.

• Supplementary views – Optional. It’s usually used to implement the header or footer views of sections. (We’ll 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. (We’ll cover this in the next chapter)

34

Figure 15-1. Photos app showing photos in grid layout

Page 36: Learn Ios7 Programming Preview

Previously, we covered the basics of UICollectionView and showed you how to present items in grid layout. It’ll be interesting to spilt recipes into different sections. Let’s say, the first section contains recipes for lunch/dinner, while the other section contains recipes for drinks and desserts.

As you’ve 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, we’ll continue to work on the app and show you how to group the items into different sections. On top of that, you’ll also learn how to add header or footer view to the collection view.

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

CHAPTER 16

35

Page 37: Learn Ios7 Programming Preview

Split the Recipe Images into Two SectionsIn 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 we’d like to split the recipes into two groups, 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. 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.

Let’s 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

Page 38: Learn Ios7 Programming Preview

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 haven’t 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, we’ll 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, we’ll continue to improve the RecipePhoto app. Here are what we’re 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. We’ll 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.

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

CHAPTER 17

37

Page 39: Learn Ios7 Programming Preview

Handling Single SelectionFirst, 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 InterfaceTo 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:

38

Figure 17-1. Managing selections in RecipePhoto App

Page 40: Learn Ios7 Programming Preview

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.

INTRODUCTION TO CORE DATA

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

~ Amelia Earhart

CHAPTER 18

39

Page 41: Learn Ios7 Programming Preview

Core Data is not a DatabaseWhen 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

40

Page 42: Learn Ios7 Programming Preview

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, 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 ObjectIf 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

CORE DATA PART-2

“Nothing is impossible, the word itself says 'I'm possible'!”

~ Audrey Hepburn

CHAPTER 19

41

Page 43: Learn Ios7 Programming Preview

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 ObjectLet’s 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, let’s 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]; }}

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. Let’s 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

Page 44: Learn Ios7 Programming Preview

In this chapter, let’s 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.

LOCALIZATION

20

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

Page 45: Learn Ios7 Programming Preview

Xcode has the built-in support of localization. So it’s 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. That’s partially correct. Translating static or visible text is just part of the localization process. Localization involves other elements such as images, graphics and sound. You’ll also need to handle the different display format of numeric values, as well as, date and time.

In this chapter, we’ll show you the step-by-step on how to localize the storyboard file, strings, images and app name. As usual, we’ll demonstrate the process by building a simple app and make it available in Chinese.

Localization OverviewWe 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. We’ll localize the app together and make it available in Chinese. At the end of the chapter, you’ll have an app that supports two localizations: English and Chinese.

44

Figure 20-1. Localization settings in iOS

Page 46: Learn Ios7 Programming Preview

If you’ve studied the first few chapters, you should have a basic understanding about table view. So far, the table views that we’ve covered are of dynamic content. However, it’s 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, we’ll show you how it can done using Storyboard.

To illustrate how easy you can use Storyboard to implement static table view, we’ll build a simple Setting screen. Static table views are ideal in situations where a pre-defined number

STATIC TABLE VIEW

21

45

Page 47: Learn Ios7 Programming Preview

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, you’ll learn how to parse XML using NSXMLParser class. Of course, we’ll go through the concept by building a simple RSS reader app. Isn’t it cool?

The app that we’re going to build is very simple. It’ll load a RSS feed and display the article items on a table view. When user taps on any of the article, it’ll navigate to load the article in a web view. Figure 22-1 shows a sample screenshot of the RSS Reader app.

BUILDING A SIMPLE RSS READER APP

“It is always the simple that produces the marvelous.”

~ Amelia Barr

CHAPTER 22

46

Page 48: Learn Ios7 Programming Preview

Figure 22-1. RSS Reader App

Creating the Xcode ProjectOpen 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

Page 49: Learn Ios7 Programming Preview

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, we’ll 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, we’ll 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 taken2. Two buttons: one is used to take a new photo and the other one to select a photo from the

photo library.

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

CHAPTER 23

48

Page 50: Learn Ios7 Programming Preview

Figure 23-1. A simple camera app

Creating the Xcode ProjectLaunch 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

Page 51: Learn Ios7 Programming Preview

Previously, we covered how to create a simple camera app. In this chapter, we’re 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. We’ll 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 player’s view into a view owned by your app.

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

CHAPTER 24

50

Page 52: Learn Ios7 Programming Preview

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 OverviewLike any chapter of this book, we’ll 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, it’ll 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?

51

Figure 24-1. Simple Video App

Page 53: Learn Ios7 Programming Preview

Before we dive into the local notification tutorial, let’s 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 it’s not actively running. When a notification comes in, 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.

LOCAL NOTIFICATION

25

52

Page 54: Learn Ios7 Programming Preview

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 you’re developing a To-Do 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 it’ll be fired up at a proper time.

Okay, that’s enough for the history and background. Let’s see how to implement Local Notification and build a simple To-Do app as demo.

The To-Do App with NotificationsTo demonstrate the usage of local notification, we’ll 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

Page 55: Learn Ios7 Programming Preview

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.

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

CHAPTER 26

54

Page 56: Learn Ios7 Programming Preview

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 horizontal2. the transition style – page curl transition style or scrolling transition style3. the location of the spine - only applicable to page curl transition style4. the space between pages - only applicable to scrolling transition style to define the inter-

page 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 AppThe 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

Page 57: Learn Ios7 Programming Preview

If you read this book from the very beginning and understand the materials thoroughly, you’re now ready to move onto something more advanced. In this chapter, we’ll show you how create a slide-out navigation menu similar to the one you find in the Facebook app. If you’re 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

SLIDE-OUT SIDEBAR MENU

27

56

Page 58: Learn Ios7 Programming Preview

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. That’s better as it’s a good practice to separate static data from code.

However, both approaches face the same problem. Suppose you’ve published the Recipe app on App Store, what if you need to add more recipes or change some of the recipes?

Obviously, you’ll 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. That’s 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, you’re free to edit the recipe without rebuilding the app.

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

CHAPTER 28

57

Page 59: Learn Ios7 Programming Preview

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, we’ve 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, you’ve learnt how to retrieve objects from Parse. In this part, you’ll learn how to save new recipe to the Parse backend. Of course, you’ll learn how to delete the recipe, as well.

We will build on the Xcode project that you’ve done in Part 1. So if you haven’t gone through the project and exercise, it’s highly recommended to check out the first part of the series.

Let’s get started.

PARSE CLOUD PART-2

“Some people want it to happen, some wish it would happen, others make it

happen.”

~ Michael Jordan

CHAPTER 29

58

Page 60: Learn Ios7 Programming Preview

Getting StartedBefore moving to the coding part, let’s have a quick look at the new features. Previously, we’ve built a Recipe app to retrieve recipes from Parse and display them using PFQueryTableViewController. In this chapter, 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. Saving data to the Parse cloud

Designing the User InterfaceThe main user interface is pretty much unchanged. However, in order to let users add new recipe, we’ll add a new view controller. The “New Recipe” view controller is triggered by

59

Page 61: Learn Ios7 Programming Preview

AirDrop is Apple’s 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.

AIRDROP

30

60