Thursday, April 3, 2014

Working with UITableView in Xcode 5 Using Storyboard

When we first started the iOS programming course, we wrote a tutorial about UITableView and showed you how tocreate a simple table app using UITableView. This is one of our most popular tutorials. However, you may find it no longer works in Xcode 5. The latest version of Xcode promotes the use of Storyboard over Interface Builder. Storyboard is no longer an option when creating a new Xcode project. It’s the default. This is one of the reasons why you couldn’t follow the steps in the UITableView tutorial to create the app.
Anyway, we decide to completely update the table view tutorial for Xcode 5 and iOS 7. And here you are.
Enter the UITableView tutorial.
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.


Sample UITableView
undefined

Creating a SimpleTable Project

With an idea of table view, let’s get our hands dirty and create a simple app. Don’t just read the tutorial 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.

Xcode Project Template Selection
Xcode Project Template Selection
Click “Next” to continue. Again, fill in all the required options for the Xcode project:
Product Name: SimpleTable – This is the name of your app.
Company Identifier: com.appcoda – It’s actually the domain name written the other way round. If you have a domain, you can use your own domain name. Otherwise, you may use mine or just fill in “edu.self”.
Class Prefix: SimpleTable – Xcode uses the class prefix to name the class automatically. In future, you may choose your own prefix or even leave it blank. But for this project, let’s keep it simple and set it to “SimpleTable”.
Device Family: iPhone – Just use “iPhone” for this project.

SimpleTable Project Options
SimpleTable Project Options
Click “Next” to continue. Xcode then asks you where you saves the “SimpleTable” project. Pick any folder (e.g. Desktop) to save your project. As before, deselect the option for Source Control. Click “Create” to continue. Simply pick a folder to save your project. As you confirm, Xcode automatically creates the “SimpleTable” project based on the options you’ve provided. The resulting screen looks like this:

Main Screen of SimpleTable Project
Main Screen of SimpleTable Project

Designing the View

First, we’ll create the user interface and add the table view. Select Main.storyboard to switch to the Storyboard interface.

Storyboard for SimpleTable Project
Storyboard for SimpleTable Project
In the Object Library, select the “Table View” object and drag it into the view.

Drag a Table View from Object Library and add it to the view
Drag a Table View from Object Library and add it to the view
Resize its height a little bit, so that it doesn’t cover the status bar. Your screen should look like below after inserting the table view.

Drag a table view from Object Library
Drag a table view from Object Library

Run Your App for the First Time

Before moving on, try to run your app using the Simulator. Click the “Run” button to build your app and test it.
The Simulator screen will look like this:

SimpleTable App running in the simulator
Easy, right? You already designed the table view in your app. For now, however, it doesn’t contain any data. Next up, we’ll write some code to add the table data.

Adding Table Data

Go back to the Project Navigator and select “SimpleTableViewController.h”. Append “<uitableviewdelegate, uitableviewdatasource="">” after “UIViewController”. Your code should look like below:
1
2
3
4
5
#import <UIKit/UIKit.h>

@interface SimpleTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

@end
The “UITableViewDelegate” and “UITableViewDataSource” are known as protocol in Objective-C. Basically, in order to display data in Table View, we have to conform to the requirements defined in the protocols and implement all the mandatory methods.

UITableViewDelegate and UITableViewDataSource

Earlier, we’ve added the “UITableViewDelegate” and “UITableViewDataSource” protocols in the header file. It may be confusing. What’re they?
The UITableView, the actual class behind the Table View, is designed to be flexible to handle various types of data. You may display a list of countries or contact names. Or like this example, we’ll use the table view to present a list of recipes. So how do you tell UITableView the list of data to display? UITableViewDataSource is the answer. It’s the link between your data and the table view. The UITableViewDataSource protocol declares two required methods (tableView:cellForRowAtIndexPath and tableView:numberOfRowsInSection) that you have to implement. Through implementing these methods, you tell Table View how many rows to display and the data in each row.
UITableViewDelegate, on the other hand, deals with the appearance of the UITableView. Optional methods of the protocols let you manage the height of a table row, configure section headings and footers, re-order table cells, etc. We do not change any of these methods in this example. Let’s leave them for the later tutorial.
Okay, let’s continue to code the app. Select “SimpleTableViewController.m” and define an instance variable for holding the table data.
1
2
3
4
@implementation SimpleTableViewController
{
    NSArray *recipes;
}
In the viewDidLoad: method, add the following code to declare the “recipes” array. We initialize an array with a list of recipes.
1
2
3
4
5
6
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Initialize table data
    recipes = [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];
}

What is an array?

An array is a fundamental data structure in computer programming. You can think of an array as a collection of data elements. Consider the recipes array in the above code, it represents a collection of textual elements. You may visualize the array like this:
recipes array
Each of the array elements is identified or accessed by an index. An array with 10 elements will have indices from 0 to 9. That means, recipes[0] returns the first element of the “recipes” array.
In Objective C, NSArray is the class for creating and managing array. You can use NSArray to create static array for which the size is fixed. If you need a dynamic array, use NSMutableArray instead.
NSArray offers a set of factory methods to create an array object. In our code, we use “arrayWithObjects” to instantiate a NSArray object and preload it with the specific elements (e.g. Hamburger).
You can also use other built-in methods to query and manage the array. Later, we’ll call the “count” method to query the number of data elements in the array. To learn more about the usage of NSArray, you can always refer to Apple’s official document.
Finally, we have to add two datasource methods: tableView:numberOfRowsInSection and tableView:cellForRowAtIndexPath. These two methods are part of the UITableViewDataSource protocol. It’s mandatory to implement the methods when configuring a UITableView. The first method is used to inform the table view how many rows are in the section. So let’s add the below code. The count: method simply returns the number of items in the “tableData” array.
1
2
3
4
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [recipes count];
}
Next, we implement the other required methods.
1
2
3
4
5
6
7
8
9
10
11
12
13
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"SimpleTableCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

    cell.textLabel.text = [recipes objectAtIndex:indexPath.row];
    return cell;
}
The cellForRowAtIndexPath: method is called every time when a table row is displayed. The below illustration will give you a better understanding about how UITableView and UITableDataSource work.

How UITableView and UITableDataSource work together
How UITableView and UITableDataSource work together
Okay, let’s hit the “Run” button and try out your final app. Oops! you still got a blank app! It’s the same as before.
Why is it still blank? We’ve already written the code for generating the table data and implemented the required methods. But why the Table View isn’t shown up as expected?
There is still one thing left.

Connecting the DataSource and Delegate

Like the “Hello World” button in the first tutorial, we have to establish the connection between the Table View and the two methods we just created.
Go back to the Main.storyboard. Select the table view. Press and hold the control key on your keyboard, click the table view and drag to the “Simple Table View Controller” icon of the dock. Your screen should look like below:

Connecting Table View with its Datasource and Delegate
Connecting Table View with its Datasource and Delegate
Release both buttons and a pop-up shows both dataSource & delegate. Select “dataSource” to make a connection between the Table View and its data source. Repeat the above steps and make a connection with the delegate.

Connect dataSource and delegate
Connect dataSource and delegate
That’s it. To ensure the connections are linked properly, you can select the Table View again. In the upper part of the Utility area, you can reveal the existing connections in the “Connection Inspector” (i.e. the rightmost tab).

Show the Connections Inspector
Show the Connections Inspector

Test Your App

Finally, it’s ready to test your app. Simply hit the “Run” button and let the Simulator load your app:

Simple Table View App

Add Thumbnail to Your Table View

The table view is too plain, right? What about adding an image to each row? The iOS SDK makes it extremely easy to do this. You just need to add a line of code for inserting a thumbnail for each row.
First, download this sample image. Alternatively, you can use your own image but make sure you name it “creme_brulee.jpg”. In Project Navigator, right-click the “SimplyTable” folder and select “Add Files to SimpleTable…”.

Show the Connections Inspector
Select the image file you just downloaded and check “Copy items to destination group’s folder” checkbox. By selecting the option, the image will be copied to the project folder. Click “OK” to add the file.

Pick your image file and add to the project
Pick your image file and add to the project
Now edit the SimpleTableViewController.m. Add the following line of code in “tableView:cellForRowAtIndexPath” method and put it right before “return cell”:
1cell.imageView.image = [UIImage imageNamed:@"creme_brelee.jpg"];
Your code should look like this after editing:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"SimpleTableCell";
   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
   
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }
   
    cell.textLabel.text = [recipes objectAtIndex:indexPath.row];
    cell.imageView.image = [UIImage imageNamed:@"creme_brelee.jpg"];
   
    return cell;
}
The table view cell comes with a default property for showing image. The line of code simply loads the image and display it in the image area of the table cell. Now, hit the “Run” button again and your SimpleTable app should display the image in each row.

Simple Table View App

Summary

It’s simple to create a table view, right? Table view is one of the most commonly used elements in iOS programming. If you’ve followed the tutorial and build the app, you should have a basic idea about how to create the table view. I try to keep everything simple in the demo app. In reality, the table data will not be stored directly in the code. Usually, it’s loaded from file, database or somewhere else. In later tutorials, you’ll learn how to store and load the table data from a file. But before moving on, make sure you thoroughly understand how the table view works. Otherwise, go through the tutorial again.

The Fast, Secure and Professional PHP Framework with yiiframework

About Yii

Yii is a high-performance PHP framework best for developing Web 2.0 applications.
Yii helps Web developers build complex applications and deliver them on-time.
Yii is pronounced as Yee or [ji:], and is an acroynym for "Yes It Is!". This is often the accurate, and most concise response to inquires from those new to Yii:
Is it fast? ... Is it secure? ... Is it professional? ... Is it right for my next project? ... Yes, it is!
undefined
Yii is a free, open-source Web application development framework written in PHP5 that promotes clean, DRY design and encourages rapid development. It works to streamline your application development and helps to ensure an extremely efficient, extensible, and maintainable end product.
Being extremely performance optimized, Yii is a perfect choice for any sized project. However, it has been built with sophisticated, enterprise applications in mind. You have full control over the configuration from head-to-toe (presentation-to-persistence) to conform to your enterprise development guidelines. It comes packaged with tools to help test and debug your application, and has clear and comprehensive documentation.
To learn more about what Yii brings to the table, check out the features section.

History

Yii is the brainchild of its founder, Qiang Xue, who started the Yii project on January 1, 2008. Qiang previously developed and maintained the Prado framework. The years of experience gained and developer feedback gathered from that project solidified the need for an extremely fast, secure and professional framework that is tailor-made to meet the expectations of Web 2.0 application development. On December 3, 2008, after nearly one year's development, Yii 1.0 was formally released to the public.
Its extremely impressive performance metrics when compared to other PHP-based frameworks immediately drew very positive attention and its popularity and adoption continues to grow at an ever increasing rate.

Credits

Yii incorporates many ideas and work from other well-known Web programming frameworks and applications. Below is a short list of those from which Yii drew inspiration.
  • Prado: This is the major source of ideas for Yii. Yii adopts its component-based and event-driven programming paradigm, database abstraction layers, modular application architecture, internationalization and localization, and many of its other features and patterns.
  • Ruby on Rails: Yii inherits its spirit of convention over configuration. Yii also referenced its implementation of the active record design pattern for its ORM layer.
  • jQuery: This is integrated in Yii as the foundational JavaScript framework.
  • Symfony: Yii referenced its filter design and plug-in architecture.
  • Joomla: Yii referenced its modular design and message translation scheme.
undefined
undefined
Rate this blog entry:
0
1
2
3
4
5
6
7
8
9

How To Scan QR Code Using AVFoundation Framework

iOS 7 brings a wealth of new features that set it apart from all other mobile operating systems. Both major additions and minor improvements have been made, offering developers new or updated frameworks and APIs to work with, and the opportunity to provide single users with a much richer experience. The AVFoundation framework is just one of them, as it has accepted great enhancements and new class additions that make even more tools available. One of the new features that the AVFoundation incorporates, is the ability to discover and read bar codes in real-time, and one of the supported bar code types that we especially interested in at this tutorial, is the QR Code.
A Quick Response Code (QR Code) is actually a two-dimensional (2D) barcode. Instead of the vertical lines like those that the well-known barcode contains, a QR Code can have its lines designed in both horizontal and vertical directions. The data that’s being encapsulated into such a code, is read by devices specificly designed for this job, or by smart devices (smartphones, tablets) using the appropriate software. A QR Code can store a great amount of data (in relation to the ordinary barcode), so there is a variety of information that can be encoded in it. Some typical content examples of a QR Code are:
  • URL
  • Phone number
  • Simple text
  • SMS text
QR Codes are used mainly for marketing reasons, but not only. One can create a QR Code to use on its website, or on any other place that may wants.
QRCode Featured
undefined
undefined
Thanks to iOS 7, creating applications that can scan and translate a QR Code has been really a piece of cake. So, if you have ever been tempted to create such an app, or you are just curious to learn more about all these, then just keep reading!

Demo App Overview

The demo application that we are going to implement in this tutorial is fairly simple and straightforward. It is going to be universal, meaning that it will be able to work in both iPhone and iPad, so you can run it on any device you might have with iOS 7 installed on it. Right next is shown a figure of the outcome in iPhone:
QR Code Demo App for iPhone
For the iPad, the interface is more or less the same:
QR Code Demo App for iPad
Before I proceed to a discussion regarding the demo figures above, it’s important to underline at this point that any barcode scanning, including QR codes, is totally based on video capturing, that’s why AVFoundation framework supports the barcode reading feature. Keep this info on mind, as it’s the starting point for the entire application.
Even though it’s not hard to figure out what all subviews layed on the interface are for, I’ll make a quick reference on them, so it’ll become absolutely clear what our app is going to contain.
So, beginning from top to bottom, at first there is a UIView view, which is going to be the container for the preview layer of the video captured by the device. A UILabel exists on top of it, simply prompting to tap on the start button to begin reading a QR code. Right next, another UILabel plays the role of the status log while a code is being read, and finally a toolbar lies at the bottom of the view, with one bar button item only which will be used to start and stop the capturing.
Here is how the demo application is going to work:
Initially, when the app is launched, the interface shown in the figure above is first displayed. By tapping the start bar button at the toolbar, a video capturing session is initiated in order to scan for QR codes. Once that happens, the start button’s title changes to Stop, while its functionality changes as well with aim to enable us to stop capturing at any time.
The status label is going to show three different messages, depending on the scanning state:
  1. When a code scanning is not yet performed.
  2. When a code scanning is in progress.
  3. When a scan has been completed and the contained information has been translated and is ready to be displayed.
Also, a sound effect (a beep sound) is being played every time a QR code has been successfully read to make our app more vivid and interactive.
Note that this application cannot be tested on the Simulator, neither to a device without a camera, as everything is based on real-time video capturing. Therefore, you’ll need to connect your device and run it there if you want to see the application live.

Building the Demo App

Ready to take off? Let’s begin by launching the Xcode. In the Welcome screen, select to create a new project.
Xcode Welcome
In the project creation guide under the iOS section, select the Application category and then select the Single View Application template. Click Next to proceed.
Select Xcode Project Template
Next, give a name to the project. In the Product Name field add the QRCodeReader value. Also, in theDevices drop down menu select the Universal value in order to let your app run in both iPhone and iPad devices. Click Next to continue.
Set Xcode Project Details
In the last window, select a directory to save the project and click on the Create button.
Xcode creates the project and makes any necessary initial, default configuration is required. Now we are ready to start building.

Setting Up the User Interface

Our application is universal, so it’s needed to create the interface for both the iPhone and the iPad. Let’s begin from the iPhone, so click on the Main_iPhone.storyboard to bring the Interface Builder up. Initially, you should see only an empty view controller, just like the next image:
Initial Interface for QR Code Demo
Here is a list of all the controls you need to drag and drop in the view of the view controller, along with all properties that need to be set in order to create an interface similar to the wanted one.
  • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">UIView
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Frame: X=20 Y=40 Width=280 Height=350
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Background Color: Black
  • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">UILabel Add this as a subview to the previous view
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Frame: X=17 Y=164 Width=247 Height=21
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Color: White
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Text: Tap on Start! to read a QR Code
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Font: System Bold 15.0
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Text Alignment: Center
  • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">UILabel
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Frame: X=20 Y=448 Width=280 Height=21
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Color: R=0 G=255 B=0
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Text: QR Code Reader is not yet running…
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Font: System 15.0
  • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">UIToolbar
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Frame: X=0 Y=524 Width=320 Height=44
  • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">UIBarButtonItem (already existing on the toolbar)
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Title: Start!
  • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">UIBarButtonItem
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">New Flexible Space Bar Button Item on the left side of the start button.
  • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">UIBarButtonItem
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">New Flexible Space Bar Button Item on the right side of the start button.
After you’re done, the interface should look like the next one:
QR Code iPhone Interface
Here is the respective list with all the controls required to setup the interface for the iPad, along with the properties you need to configure.
  • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">UIView
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Frame: X=44 Y=40 Width=680 Height=840
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Background Color: Black
  • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">UILabel Add this as a subview to the previous view
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Frame: X=20 Y=329 Width=640 Height=41
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Color: White
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Text: Tap on Start! to read a QR Code
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Font: System Bold 24.0
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Text Alignment: Center
  • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">UILabel
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Frame: X=20 Y=448 Width=280 Height=21
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Color: R=0 G=255 B=0
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Text: QR Code Reader is not yet running…
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Font: System 17.0
  • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">UIToolbar
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Frame: X=0 Y=980 Width=768 Height=44
  • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">UIBarButtonItem (already existing on the toolbar)
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">Title: Start!
  • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">UIBarButtonItem
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">New Flexible Space Bar Button Item at the left side of the start button.
  • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">UIBarButtonItem
    • http://www.appcoda.com/wp-content/themes/eleven40/images/list.png); list-style-type: none; word-wrap: break-word; background-position: 0% 0%; background-repeat: no-repeat no-repeat;">New Flexible Space Bar Button Item at the right side of the start button.
Here is how the iPad interface should now look like:
QR Code for iPad Interface
So far, so good. For both devices the interface is ready, but we are not finished yet. We need to create IBOutlet methods and connect them to the controls we need to touch in code. Open theViewController.h file, and add the following IBOutlet property declarations:
1
2
3
4
5
6
7
@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIView *viewPreview;
@property (weak, nonatomic) IBOutlet UILabel *lblStatus;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *bbitemStart;

@end
As you see, we need properties for the video container view, the status label and the start bar button item. Besides these properties however, now it’s the best time to declare an IBAction method which we will connect to the start bar button item in order to make it start and stop video capturing. Therefore, right after the last property, add the next line:
1- (IBAction)startStopReading:(id)sender;
Let’s make the connections now. Open the Main_iPhone.storyboard file and Control-Click or Right-Click on the View Controller object, inside the Document Outline pane. In the black popup window that appears, you can see all of the IBOutlet properties that were previously declared under theOutlets section. For each one of them, click on the circle on the right side and drag and drop to the appropriate control. The next image will make this procedure clear:
Connect IBOutlet
Follow the same steps to connect the startStopReading: IBAction method to the start bar button item. The IBAction method exists under the Received Actions section in the black popup window.
As a reminder, don’t forget to do the same job in the Main_iPad.storyboard file.

QR Code Reading Implementation

Up to now we have created the project, we have setup the interface and we have done all necessary configurations on the controls of our application. Time to make a deep dive and write the necessary code that will give life to the most important feature, the QR code reading.
The best point to start writing code is our IBAction method, the startStopReading:, which is already declared and connected to the start bar button item. However, before we begin implementing it, let’s remember something; while I was presenting the demo app and the way it’s going to work, I said that once the video capturing begins, the start button becomes a stop button and vice versa. Programmatically, that means that we need to find a way that lets the app know when to perform the start functionality, and when to perform the stop functionality. Well, what’s a better way than a flag?
If you haven’t done already, open the ViewController.m file. Navigate yourself at the top of it, in the private interface section, and add the following flag:
1
2
3
@interface ViewController ()
@property (nonatomic) BOOL isReading;
@end
It’s quite obvious by its name that, when the isReading variable is NO (false), then the app is not scanning for a QR code and the video capture functionality should start when the bar button is tapped. The exact opposite happens when the variable is set to YES (true). I would strongly advice that when declaring member variables, then the next step that should be done is to give them their initial value, as the most probable scenario is that you are going to forget to do so later. So, let’s go inside theviewDidLoad method to set the initial value for our flag:
1
2
3
4
5
6
- (void)viewDidLoad
{
    [super viewDidLoad];

    _isReading = NO;
}
Now we are absolutely ready to implement the startStopReading: IBAction method. Write the following code snippet and then we’ll discuss it a bit:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
- (IBAction)startStopReading:(id)sender {
    if (!_isReading) {
        if ([self startReading]) {
            [_bbitemStart setTitle:@"Stop"];
            [_lblStatus setText:@"Scanning for QR Code..."];
        }
    }
    else{
        [self stopReading];
        [_bbitemStart setTitle:@"Start!"];
    }  
   
    _isReading = !_isReading;
}
At first, we check if the isReading flag is NO, meaning that currently no QR code scanning is taking place. If that’s the case, then we call the startReading method, which we are going to implement in a while. If everything goes well when calling this method, then we change the bar button item’s title toStop and we set another message on the status label. However, if the app is currently scanning for a QR code and the isReading flag is YES, then we call the stopReading method (yes, we’ll implement this one later too), and we also set the title of the bar button item to Start!. Finally, no matter what the case is, we set in the isReading flag the exact opposite value of the one that currently has.
As you just saw, we used two methods that we haven’t yet implemented. We will begin doing so by thestartReading, which as you imagine, is one of the most important methods in this app. First of all, we need to declare it, so go to the private interface section and add the next declaration:
1
2
3
4
5
6
@interface ViewController ()
@property (nonatomic) BOOL isReading;

-(BOOL)startReading;

@end
Don’t leave there yet. Before we move to implementation, we need to declare a couple of objects that we’ll need right next. So, add the new lines shown in the snippet below:
1
2
3
4
5
6
7
8
@interface ViewController ()
@property (nonatomic) BOOL isReading;

@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;

-(BOOL)startReading;
@end
At this point Xcode will probably complain about the AVCaptureSession and theAVCaptureVideoPreviewLayer classes. That’s because we still haven’t imported the AVFoundation framework. Before we fix this, go into the viewDidLoad method and make the captureSession object nil.
1
2
3
4
5
6
7
- (void)viewDidLoad
{
    [super viewDidLoad];
    _isReading = NO;
   
    _captureSession = nil;
}
Now, open the ViewController.h file and at the top of it, import the AVFoundation framework.
1#import <AVFoundation/AVFoundation.h>