+1 (208) 254-6996 essayswallet@gmail.com

See how to create an example web service in Android. Page 174,   Chapter 6   Getting Started with Android – Alternative Formats See how to create an example web service in iOS. Page 214,   Chapter 7   Getting Started with iOS – Alternative Formats

For submission : Read carefully about 2 different approaches for creating a web service from above. Then

Don't use plagiarized sources. Get Your Custom Essay on
Mobile App Assignment
Just from $13/Page
Order Essay

(a) compare the two approaches and

(b) explain 2 advantages of each approach relative to the other.

Getting Started with Android WHAT’S IN THIS CHAPTER?

! Deciding to target Android as your mobile platform

! Getting the tools you need to develop Android

! Creating a new project

! Creating the Derby project in Android

Android Inc. was initially started in 2003, out of a frustration with the smartphone market as it existed at the time. It was acquired by Google in 2005.

The hardware side of Android is supported by the Open Handset Alliance (OHA), which is a conglomeration of many handset manufacturers, and the software is maintained by the Android Open Source Project, which is led by Google.

Android had its fi rst major release in late 2008; the fi rst major phone company to support it was T-Mobile, and the original handset was the HTC Dream (G1).

The Android OS was built on a modifi ed Linux kernel and applications are written in Java. By using Java as the development framework for the applications, Android enables you to develop your application on all major platforms.

By leveraging the Eclipse IDE, Android affords the user almost the exact same user experience for development on all major OS platforms.

Additionally, when researching Android you may come across the name Dalvik. It is the virtual machine that runs on the Android device, and your applications run within it. What does this mean to developers? Because your applications run inside this virtual space, it provides a level of security to the base OS. Also, Dalvik has been designed with performance in mind. As of Android 2.2 it also provides just-in-time compilation to your apps (because Dalvik requires specially compiled .dex fi les and not just the standard .class fi les generated in a normal Java compilation).


c06.indd 151c06.indd 151 28/07/12 6:01 PM28/07/12 6:01 PM


WHY TARGET ANDROID? Among the many reasons to target the Android platform, fi rst and foremost is cost. On average you can get an Android smartphone for a fraction of the cost of an iPhone. They may not have commensurate features, but thrift is a major component for new smartphone buyers.

Next is fl exibility. More types of Android devices are available, so if your application fi ts a specifi c niche market, there is probably a device that would support your needs already in production. At the time of writing, there are effectively two iOS devices (iPhone/iPod touch and iPad); four if you include the retina display versions, versus roughly 15 form factors to develop for.

If you are already a Java developer, adding Android to your repertoire is a snap. What Java is to Android, Cocoa is to CocoaTouch and C# is to Silverlight. All of the frameworks that mobile developers use are a combination of subsets and supersets of the functionality of a given technology.

Identifying an application that exists on another platform but does not yet exist on Android is another perfectly good reason to target Android. That being said, you should do some research, because if a developer has targeted iOS or BlackBerry as the primary platform, you have to assume that Android is potentially on the horizon.

WHO SUPPORTS ANDROID? HTC, LG, Motorola, and Samsung are the major players in the Android smartphone market. Archos, Dell, Samsung, and Toshiba hold the largest pieces of the Android tablet market. You should note that Amazon’s Kindle Fire and Nook Color are up-and-comers and use a customized version of the Android tablet (Version 3) OS on their devices.

ANDROID AS COMPETITION TO ITSELF Because Android was designed to be run on many different types of devices, created by many different manufacturers (as opposed to the closed system that Apple has maintained), it has left itself open to the will of said manufacturers. Because of the open nature of the Android OS, it is commonplace for manufacturers to create vendor-specifi c builds of Android, and when this happens you are beholden to them for OS updates. Additionally in these custom builds, vendor-specifi c limitations have arisen such as the vendor-specifi c market. You then have another hurdle to cross when releasing your application for sale to the public because some devices may not be able to purchase it because of these limitations.

Another issue that has cropped up is the lack of over-the-air (OTA) distribution of OS updates by cellular carriers. Often your device is perfectly capable of running a later version of the Android software, but carriers are often slow to distribute that to their customers.

Multiple Markets and Market Locks Depending on your version of Android, and depending on the manufacturer of a given device, you may fi nd yourself locked into using a vendor-specifi c Android marketplace. Additionally, application

c06.indd 152c06.indd 152 28/07/12 6:01 PM28/07/12 6:01 PM

Getting the Tools You Need ” 153

vendors can list their application not only on Google Play or vendor-specifi c marketplaces, but also on the Amazon App Store. You often fi nd on cheap and imported Android devices a version of Google Play that is maintained by the manufacturer. They pick and choose what applications are available from the whole set in the marketplace. You should develop as you expect to be available to all Android devices; just note when purchasing large quantities for an enterprise deployment that you will have to watch out for these inconsistencies.

The version of the Android SDK that you need to support depends on what devices you want to support. If you want to target most phones available right now, you should support Android 2.2 or 2.3. “Gingerbread” (2.3) is the last widely available version for those devices. The Android 3.x versions are for tablets, such as the Samsung Galaxy Tab. The Android 4.x versions are the newest, and are a combination of the Android 2.x and Android 3.x functionality meant to pull back on the version splintering seen in devices, but not many devices currently in release support it.

Once you have decided on a version to deploy your application against, you need to set up your development environment. In the next section you will learn all about confi guring your IDE, Java and Android SDKs, and building emulators.

GETTING THE TOOLS YOU NEED This section paraphrases the installation instructions from the Android Developer section, and we added some personal notes from our experiences.

Downloading and Installing JDK The fi rst thing that you need to do to develop Android applications is to visit http://www.oracle .com/technetwork/java/javase/downloads/index.html and ensure that you have the Java JDK installed. Because so many different acronyms and versions appear on the Java download website, Figure 6-1 points you in the direction you need to get past all of the potential distractions on that site.

The JDK is the Java Development Kit. You need this package to do any Java development on your machine, Android or otherwise. Be sure to look for the Java Platform, Standard Edition JDK.

Downloading and Installing Eclipse

After you have successfully installed the JDK, you will need a development environment. The open source IDE Eclipse is recommended by Android directly in its documentation. You are not limited only to Eclipse, but the tooling has been honed over time to be the easiest solution to

FIGURE 6!1: JDK download page

c06.indd 153c06.indd 153 28/07/12 6:01 PM28/07/12 6:01 PM


get up and running. Figure 6-2 shows the Eclipse download page (www.eclipse.org/downloads). Download the version of Eclipse Classic that is appropriate for your operating system.

FIGURE 6!2: Eclipse download site

Downloading and Installing the Android SDK After you have installed the Eclipse IDE, you need to install the Android Software Developer Kit (http://developer.android.com/sdk/index.html). This includes all the tools necessary to build Android apps, because the SDK is not built directly into Eclipse. Figure 6-3 shows the Android SDK download page; make sure to get the right version for your OS.

Don’t use the installer for 64-bit Windows. Just get the zip fi le and unzip it to c:\Android. At the time of writing the installer package has diffi culty fi nding the Java SDK installed on the machine.

For Mac deploy it to /android in your root volume.

FIGURE 6!3: Android SDK download page

c06.indd 154c06.indd 154 28/07/12 6:01 PM28/07/12 6:01 PM

Getting the Tools You Need ” 155

Downloading and Confi guring the Eclipse ADT Plug-in After you have installed the Android SDK you need the ADT plug-in. What this does is add the features necessary to create Android Projects (and Android Test Projects), because they are not bundled with the base Eclipse install. Additionally, the plug-in adds debugging tools to Eclipse to help during the Android development process. Figure 6-4 shows the interface for installing the ADT plug-in. You will also use this interface when upgrading ADT. The tooling generally gets a revision when a new version of the Android OS is released.

FIGURE 6!4: Installing the ADT plug-in

Use the Update Manager feature of your Eclipse installation to install the latest revision of ADT on your development computer. Follow these steps:

1. Start Eclipse and select Help # Install New Software. 2. Click Add in the top-right corner. 3. In the Add Repository dialog box that appears, enter ADT plug-in for the name and the

following URL for the location: https://dl-ssl.google.com/android/eclipse/.

4. Click OK. If you have trouble acquiring the plug-in, try using “http” in the Location URL instead of “https” (“https” is preferred for security reasons).

5. In the Available Software dialog box, select the checkbox next to Developer Tools and click Next.

c06.indd 155c06.indd 155 28/07/12 6:01 PM28/07/12 6:01 PM


6. The next window shows a list of the tools to be downloaded. Click Next. 7. Read and accept the license agreements and then click Finish. If you get a security warning

saying that the authenticity or validity of the software can’t be established, click OK.

8. When the installation completes, restart Eclipse. Once you have downloaded the ADT plug-in you need to set it up to talk to the Android SDK that you downloaded earlier. This allows Eclipse to build, run, and debug Android applications without needing to open a terminal or command shell. Figure 6-5 shows where you need to add the link to the Android SDK in the Eclipse preferences.

After you’ve successfully downloaded the ADT, the next step is to modify your ADT preferences in Eclipse to point to the Android SDK directory (see Figure 6-5):

1. Select Window # Preferences to open the Preferences panel. In Mac OS X, click Eclipse # Preferences.

2. Select Android from the left panel. 3. You may see a dialog box asking whether you want to send usage statistics to Google. If

so, make your choice and click Proceed. You cannot continue with this procedure until you click Proceed.

4. For the SDK Location in the main panel, click Browse and locate your downloaded SDK directory.

5. Click Apply and then click OK.

FIGURE 6!5: ADT confi guration screen

c06.indd 156c06.indd 156 28/07/12 6:01 PM28/07/12 6:01 PM

Getting the Tools You Need ” 157

Installing Additional SDK Components The last step in preparing your development environment for Android is to download additional Android OS packages. This enables you to build applications that target that OS, and also gives you the tools you need to emulate a device running that OS on which to test all of your applications, whether or not they have been targeted to that OS version. Figure 6-6 shows just how many options you have when looking to target Android OS versions.

FIGURE 6!6: Working with the SDK Manager

Correctly confi guring and using this tool will ensure that you have all the latest SDKs and utilities afforded to you. Note that you will not necessarily need all of the versions of the SDKs listed in Figure 6-6; this was merely to illustrate the full breadth of your options.

Loading the Android SDK Manager in Eclipse takes only a few steps:

1. Open Eclipse. 2. Select Window # Android SDK and AVD Manager.

c06.indd 157c06.indd 157 28/07/12 6:01 PM28/07/12 6:01 PM


3. Select Available Packages in the left panel. This reveals all of the components that are cur- rently available for download from the SDK repository.

4. Select the component(s) you’d like to install and click Install Selected. 5. Verify and accept the components you want (ensure each one is selected with a green check-

mark) and click Install. The components will now be installed into your existing Android SDK directories.

I recommend that you download and install an Android 2.2.x, Android 2.3.x, and Android 3.x version. This will give you the latest two handset-specifi c versions of Android, and the current tablet version of Android. As Android 4.0 is so new, you may choose to get it, but understand that you may need to purchase a newer device to test apps targeted to that version.

Development The following sections discuss the application layout and Android app development.

Creating a New Project First things fi rst — you need to create a new Android project. The line highlighted in Figure 6-7 is the type of project you want.

FIGURE 6!7 Creating a new Android project

c06.indd 158c06.indd 158 28/07/12 6:01 PM28/07/12 6:01 PM

Getting the Tools You Need ” 159

First you need to name your application and add it to a workspace. Think of a workspace as the folder in which your application resides. Figure 6-8 illustrates what the New Android Project screen looks like.

After you have named your application you will need to give it a package name, set the minimum SDK required to run your application, and name the initial Activity that will run when your application runs. If you want to add a test project to your workspace, you can do so at this time. Figure 6-9 shows a completed Application Info step in the new project wizard.

An important note at this point: Make sure that your package name is unique. The standard format for package names is com.companyName.applicationName. This must be unique because that is how it is known on the Android device and in the Android Market. When you make updates you can make them only within your package name. If you change your package name there will be no upgrade path between versions.

The minimum SDK required is generally set when you are leveraging a permission or piece of functionality that did not exist when the core Android version was released, or if you want to target a specifi c type of device (tablet versus handset). The major jumps are between 1.6 and 2.1, 2.3 and 3.x, and 3.x and 4.x. Figure 6-10 shows you all of the SDKs that you have installed that you can target when creating your application. Please note that the reason this screen is full of SDKs is because I took the time to download them all for demonstration purposes.

FIGURE 6!8: Naming your project

FIGURE 6!9: Confi guring application information

c06.indd 159c06.indd 159 28/07/12 6:01 PM28/07/12 6:01 PM


This step is also very important when building your application. The minimum SDK version you set specifi es the lowest possible version of the SDK in which your application will run, and it is the primary version in which your application will run. Android 1.5 is the lowest version of the SDK still supported, and Android 4.0.3 (at the time of this writing) is the highest.

FIGURE 6!10: Choosing the SDK version for your app

Figure 6-10 shows a Google version of the SDK alongside all of the versions I have installed on my machine. The Google APIs add additional functionality to each API Level. Please use your best judgment when deciding whether to use the Google APIs, and research if you need the functionality they provide.

Project Structure The major sections to note in Figure 6-11 are the src and res folders and the AndroidManifest .xml fi le. It shows the project layout for the application that I have been building in the previous steps.

c06.indd 160c06.indd 160 28/07/12 6:01 PM28/07/12 6:01 PM

Getting the Tools You Need ” 161

All of your code lives within your src folder, under your Package Namespace. The res folder holds layouts and resources for different hardware specs. HDPI, LDPI, and MDPI are the resolutions for which you can create images. The layout subfolder holds all of your XML layouts. These are how your application gets rendered. The code will be how to populate these layouts. All of your XML layouts are stored in the layout subfolder of res, and your code will be linked under the namespace in your src folder of the project view.

The Android Manifest is the heart of your application. It holds the entire confi guration of your app (Figure 6-12) — the permissions you request (Figure 6-14), the application attributes (Figure 6-13), and links to instrumentation to be attached to your app. You can edit this in Eclipse’s Manifest Editor or in XML (Figure 6-15) because that is how it is saved.

FIGURE 6!11: Basic project structure

FIGURE 6!12: Main Manifest Editor

c06.indd 161c06.indd 161 28/07/12 6:01 PM28/07/12 6:01 PM


The Manifest Editor is where the initial information of your application is stored when you create it. This interface also has links to export your application. Exporting is necessary when submitting your app to Google Play. In Eclipse there is a specifi c menu option and wizard that expedites the submission process.

Figure 6-13 shows all of the base properties that can be set for a given application in the app’s AndroidManifest.xml fi le. The most common properties to edit are the Label (the text shown under the icon, often referenced in a resource fi le) and Icon (the icon shown in the launcher UI of your device, the icon your users will click on to launch the app).

FIGURE 6!13: Manifest Application Info Editor

The spartan view shown in Figure 6-14 is the Permissions Editor. Here you can add permission requests to your application. The most common one is android.permission.INTERNET, which allows the application to use the device Internet connectivity. This, along with GPS and accelerometer, are the permissions you will add to the Derby Names application.

c06.indd 162c06.indd 162 28/07/12 6:01 PM28/07/12 6:01 PM

Getting the Tools You Need ” 163

Last is the XML Editor shown in Figure 6-15. As you make changes in the other tabs they are refl ected here. If you feel more comfortable editing the XML by hand you can use this interface to add, update, and remove properties as you see fi t.

FIGURE 6!14: Android Manifest Permissions Editor

FIGURE 6!15: Android Manifest XML Editor

c06.indd 163c06.indd 163 28/07/12 6:01 PM28/07/12 6:01 PM


Android Basics You have two options for starting your application. You can build the layout you would like to populate, or you can build the code that will populate the layout. Either is acceptable; it just depends on what you feel most comfortable with.

Creating User Interfaces This section describes the common widgets that come with Android, and shows examples of the different layout elements you can use to coordinate the fl ow of your application’s activities.

Basic Android UI Elements All of the basic elements in Android are stored in the android.widgets namespace in the SDK.

The most commonly used elements include:

! Button: This is a standard button element.

The following XML specifi es the layout of the Button widget:

<Button android:layout_height=”wrap_content” android:layout_width=”wrap_content” android:id=”@+id/button” android:text=”Click Me” android:onClick=”btnClick” />

Code: This code is necessary to handle the Click event noted in the XML layout.

public void btnClick (View view) { //Do Something. }

! TextView: When I see this I want to think text box, but it isn’t a text box. TextView is effectively the same as a label in other languages. It is just a place to display text.


<TextView android:id=”@+id/textview” android:layout_width=”fill_parent” android:layout_height=”fill_parent” android:text=”Hello World”/>


TextView tvToShow = (TextView)this.findViewById(R.id.textview); tvToShow.setText(“Ta-Dah!”);

! EditText: This is the text box widget. You can edit the contents of the text box and save those values in code.

c06.indd 164c06.indd 164 28/07/12 6:01 PM28/07/12 6:01 PM

Getting the Tools You Need ” 165


<EditText android:id=”@+id/txtUsername” android:hint=”Username” android:layout_width=”fill_parent” android:layout_height=”wrap_content” />


EditText txtUserName = (EditText) findViewById(R.id.txtUsername); String username = txtUserName.getText().ToString();

! CheckBox: This is a standard checkbox element.


<CheckBox android:id=”@+id/checkbox” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Checkbox Text” />


final CheckBox checkbox = (CheckBox) findViewById(R.id.checkbox); checkbox.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (((CheckBox) v).isChecked()) { //It’s Checked } else { //Not Checked } } });

! RadioButton: This is a standard radio button element. To really get the most bang for your buck, though, you need a RadioGroup.


<RadioGroup android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:orientation=”vertical”> <RadioButton android:id=”@+id/radio_uno” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”1 – Uno” /> <RadioButton android:id=”@+id/radio_dos” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”2 – Dos” /> </RadioGroup>

c06.indd 165c06.indd 165 28/07/12 6:01 PM28/07/12 6:01 PM



private OnClickListener radioButtonOnClick = new OnClickListener() { public void onClick(View v) { RadioButton rb = (RadioButton) v; // Do with it what you will //rb.getText(); } };

//This assigns this event to the radio buttons. RadioButton radio_uno = (RadioButton) findViewById(R.id.radio_uno); RadioButton radio_dos = (RadioButton) findViewById(R.id.radio_dos); radio_uno.setOnClickListener(radio_listener); radio_dos.setOnClickListener(radio_listener);

Figure 6-16 shows all of the major UI widgets.

! ListView: This is the element you use if you want to show lists of data. You can overload its display and put lots of elements in each row, or you can just bind a text item and a value to each. The trick is using an ArrayAdapter<T> where T is the type of object that you want bound. Additionally, creating a layout XML for how you want each item displayed is a good strategy.


<ListView android:id=”@+id/lstWords” android:layout_width=”fill_parent” android:divider=”#ddd” android:dividerHeight=”1px” android:paddingBottom=”67dp” android:layout_height=”fill_parent” />


static final String[] words = new String[]{ “Hello”, “World” }; lstWords = (ListView)findViewById(R.id.lstWords); lstWords.setAdapter new ArrayAdapter<String>(this.getApplicationContext(),R.id.list_content,words));

Basic Android Layouts and Views ! FrameLayout: This is very simplistic and can really contain only a single UI element. You

can, in fact, have multiple elements but they overlap each other by default.

The example code shown here is rendered in Figure 6-17:

FIGURE 6!16: Major UI elements all together

c06.indd 166c06.indd 166 28/07/12 6:01 PM28/07/12 6:01 PM

Getting the Tools You Need ” 167

<?xml version=”1.0” encoding=”utf-8”?> <FrameLayout android:id=”@+id/frameLayout” android:layout_width=”fill_parent” android:layout_height=”fill_parent” xmlns:android=”http://schemas.android.com/apk/res/android”> <EditText android:id=”@+id/widget46” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”EditText” android:textSize=”18sp” /> </FrameLayout>

This is a simple FrameLayout that contains a single EditText widget with the text “EditText.”

LinearLayout: This lays out your UI elements along a given direction: horizontal or vertical. Figure 6-18 is a linear layout, which contains four consecutive TextView widgets along the vertical.

FIGURE 6!17: FrameLayout rendered

FIGURE 6!18: LinearLayout rendered


<?xml version=”1.0” encoding=”utf-8”?> <LinearLayout android:id=”@+id/widget59” android:layout_width=”fill_parent” android:layout_height=”fill_parent” android:orientation=”vertical” xmlns:android=”http://schemas.android.com/apk/res/android”>

c06.indd 167c06.indd 167 28/07/12 6:01 PM28/07/12 6:01 PM


<TextView android:id=”@+id/widget60” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:background=”#ffaa0000” android:layout_marginTop=”5dp” android:layout_marginLeft=”5dp” android:text=”red” /> <TextView android:id=”@+id/widget63” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:background=”#ffaaaa00” android:layout_marginTop=”5dp” android:layout_marginLeft=”5dp” android:text=”yellow” /> <TextView android:id=”@+id/widget64” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:background=”#ff00aa00” android:layout_marginTop=”5dp” android:layout_marginLeft=”5dp” android:text=”green” /> <TextView android:id=”@+id/widget65” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:background=”#ff0000aa” android:layout_marginTop=”5dp” android:layout_marginLeft=”5dp” android:text=”blue” /> </LinearLayout>

! TableLayout: Think tables in HTML and this is the type of organization you get with this layout. TableLayouts contain rows and columns, representing a grid, and you can put other UI elements into it. The following code results in a table with two rows, each with two cells, and is visualized in Figure 6-19:

<?xml version=”1.0” encoding=”utf-8”?> <TableLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:layout_width=”fill_parent” android:layout_height=”fill_parent” android:stretchColumns=”1”> <TableRow> <TextView android:text=”Hello” android:padding=”3dip” /> <TextView android:text=”World” android:gravity=”right” android:padding=”3dip” /> </TableRow>

c06.indd 168c06.indd 168 28/07/12 6:01 PM28/07/12 6:01 PM

Getting the Tools You Need ” 169

<TableRow> <TextView android:text=”Goodbye” android:padding=”3dip” /> <TextView android:text=”User” android:gravity=”right” android:padding=”3dip” /> </TableRow> </TableLayout>

! RelativeLayout: This is the most complex layout of the four mentioned in this section. You specify relationships between UI elements to lay out your interface.

The following code represents a simple form with a TextView acting as a label for a blank EditText widget, with Cancel and OK widgets docked beneath EditText relative to the right screen boundary:

<?xml version=”1.0” encoding=”utf-8”?> <RelativeLayout android:id=”@+id/widget37” android:layout_width=”fill_parent” android:layout_height=”fill_parent” xmlns:android=”http://schemas.android.com/apk/res/android”>

<TextView android:id=”@+id/label” android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:text=”Type here:” />

<EditText android:id=”@+id/entry” android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:background=”@android:drawable/editbox_background” android:layout_below=”@id/label” /> <Button android:id=”@+id/ok” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:layout_below=”@id/entry” android:layout_alignParentRight=”true” android:layout_marginLeft=”10px” android:text=”OK” />

<Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:layout_toLeftOf=”@id/ok” android:layout_alignTop=”@id/ok” android:text=”Cancel” /> </RelativeLayout>

FIGURE 6!19: TableLayout rendered

c06.indd 169c06.indd 169 28/07/12 6:01 PM28/07/12 6:01 PM


Figure 6-20 shows how this code renders on an Android device.

Having seen the various UI elements, now is the time to get the rest of your development environment confi gured to be able to debug your app.

Creating an Android Virtual Device You need to create an Android Virtual Device (AVD) in order to debug your application in the emulator, because this “device” is what the emulator runs. Creating an AVD is quite easy. Eclipse includes a tool called AVD Manager (click Window Manager # AVD Manager). You need to name your AVD instance, choose its OS version (Target), pick a skin (with which you can customize the look and feel of the emulator) and resolution, and specify the hardware details for the device (amount of RAM, size of SD card, and sensors like Accelerometer and GPS). Once you have confi gured it to your specifi cations, click Create AVD and you are all set.

For most purposes, the stock AVD skins are fi ne for debugging, but if you would like to emulate a specifi c device (tablet or handset) either for demonstration purposes or because you want it to feel like the device you are developing for, you can use a custom skin. Although you can always set the hardware properties to mirror those of the device you are using, there is an online community (www.xda-developers.com) dedicated to making custom skins for use with the AVD. Using your favorite search engine, type the model and make of the Android device you want to emulate, and most likely you will fi nd a custom skin out there for it. Creating a new AVD with the appropriate specs and then selecting this skin gives you an emulator that looks just like the device you are testing for.

Debugging Debugging in Eclipse is easy. Instead of running your application, you click Debug As and you are off and running. Set breakpoints in your code by selecting them by the gutter next to the line numbers, and as your code progresses it will break at all your steps.

In addition to breakpoint-based debugging, you also have access to the Dalvik Debug Monitor Server (DDMS) perspective in Eclipse (see Figure 6-21). You can use DDMS to view the heap usage for a given process (your running app or anything running inside the virtual machine), track memory allocation of objects inside an app, interact with the fi lesystem of the device running the app (emulator or actual), view running threads for an application, profi le methods using tracing, read log messages using LogCat, and emulate phone and sensor data (SMS, phone calls, location [GPS]), as shown in Figure 6-22.

FIGURE 6!20: RelativeLayout rendered

c06.indd 170c06.indd 170 28/07/12 6:01 PM28/07/12 6:01 PM

Getting the Tools You Need ” 171

In Figure 6-22 you see the Emulator Control pane. In this pane you can spoof an incoming number to your emulator, to test how your application deals with that. You can also simulate text messages. The bottom pane in that page has a way to confi gure your GPS manually. This allows you to test location-based code without having to move your device.

FIGURE 6!21: DDMS perspective

FIGURE 6!22: Faking out your emulator

c06.indd 171c06.indd 171 28/07/12 6:01 PM28/07/12 6:01 PM


CONNECTING TO THE GOOGLE PLAY This section explains what is necessary to publish your application to the Google Play. There is also the Amazon Android Marketplace, which has other requirements. But because it may be more of a marketing choice than a development choice, we decided to go with the explanation of the basic Google Play distribution process.

Getting an Android Developer Account Signup is a snap for a dev account. Just make sure you have a Google account (Gmail, or Google Apps), $25 (one-time registration fee), head to https://play.google.com/apps/publish/signup, and you are all set.

Signing Your Application Signing your application with Eclipse is a relatively simple process:

1. Right-click your project in the Package Explorer and select File # Export. 2. Select Export Android Application. 3. Complete the steps of the wizard and you will have a keystore, and a signed release build of

your app ready for the market.

When you have created your keystore, make sure to guard it safely. It is the fi le you will use to sign your application every time you update, and if you lose it you cannot upgrade your application in Google Play.


When you are signing your application you can use the export tooling built into Eclipse. However, if you need to request a Google Maps API key for your application, you will need to use the keytool and jarsigner applications to get the hash of your signature. Information regarding these tools is available at http:// developer.android.com/guide/publishing/app-signing.html.

ANDROID DEVELOPMENT PRACTICES This section covers the fundamentals of developing an Android application, explaining the permissions in the Manifest and how you must always manage your navigation between Activities using the back stack.

Android Fundamentals When developing an Android app you need to account for which of the four basic components (Activities, Services, Content Providers, and Broadcast Receivers) of apps you need to include.

c06.indd 172c06.indd 172 28/07/12 6:01 PM28/07/12 6:01 PM

Android Development Practices ” 173

Activities Activities are the individual screens in your application. All of the functionality that is exposed in the UI for that screen lives in the scope of that Activity.

Services Services are components that run in a background thread. Common usages for services are to hold long-running processes, or for functions that can happen in parallel with the application (playing music from your library, or updating a web service). Be aware that when you have an application running in the background it can take processing power from the device, though contrary to popular thought it does not affect your battery life.

Content Providers Content providers are interfaces to the offl ine storage that you have within your app. If you create a suite of applications you may want to have a single point for holding all of your data. You can also leverage the Content Providers built into the Android OS. The standard set of providers in the OS allows you to get content from the Calendar, Contacts, Media Store, Messaging, and Voice Mail applications.

Broadcast Receivers Broadcast receivers are components that respond to system messages. You would use a Broadcast Receiver to catch events like the screen turning off, or the battery reaching a critical level. A common use for a Broadcast Receiver is for querying the status of the network (Wi-Fi or cellular) so that you can display the appropriate messaging to the user.

Fragments as UI Elements Starting in Android 3.x, there has been a shift in design elements to account for the signifi cant differences between the screen sizes of tablets versus handsets.Whereas normally UI design for mobile devices is very rigid, Fragments add a level of fl exibility. Fragments themselves live as a subactivity that you can reference in multiple places in your application. Fragments live within the scope of their parent activity, but can be used in multiple activities.

Ask for Permission The users of your application must approve of what functionality you want to leverage on their device. To prompt the user for what you need, and so that your device will behave as designed, you need to add permission requests in your application’s manifest. Visit http://developer.android .com/reference/android/Manifest.permission.html for a list the various permissions you can request when developing.

Depending on what version of the OS you are targeting you are afforded additional permissions. One of the newest permissions available is READ_SOCIAL_STREAM, which enables you to access the user’s social stream. One of the oldest permissions is your ability to set the given time zone, using, you guessed, it SET_TIME_ZONE.

c06.indd 173c06.indd 173 28/07/12 6:01 PM28/07/12 6:01 PM


If you try to run a piece of code in the emulator and it should be responding to fi ring events or listening to hardware, and it isn’t, make sure you have requested permission in your app. Additionally, do not request every possible permission. Applications that do this are often considered malware or at least not trustworthy by the layperson.

Mind the Back Stack Unlike iOS-based devices, all Android devices have a hardware back button. What this means is that there is something physical on the device that interrupts the UI and takes the user to the previous action. This is known in the back stack. It can be likened to a browser history or a copy/ paste clipboard. How this differs from those, though, is that it must be stateful (to provide the least jarring UI to your users). You must understand that you need to persist the state of the View when returning to it from the back stack. Additionally, if the current view affects the state of the previous view, you must update it accordingly without requiring the user to click a UI element; it needs to be able to be updated when the user backs up the stack.

Now that this chapter has covered all the major sections of development in Android, the next section will show how to build the demo Derby app in Android.

BUILDING THE DERBY APP IN ANDROID The idea of the Derby app is to build the same app over all of the mobile platforms covered in this book. The Android version is very similar to the other versions you have built thus far or will build in future chapters.

The requirements are to list the roster from the Lansing Derby Vixens roller derby team as the primary function, and then list all the roller derby teams in the world with the ability to see their team rosters.

Common Interactions The main ways to get your users around your app, and to let them know when events happen or issues arise is by using well-managed UI navigation (and the back stack), and timely use of notifi cations.

UI Navigation and Using Back Stack Because Android devices are equipped with a dedicated hardware back button, you need to make certain considerations as you pass from activity to activity within your application. The states of activities are stored in a back stack that persists and allows users to walk back through the navigation one button click at a time. Extras are stateful objects held within Intents that are the primary way that you communicate between activities. Considered “the glue between activities” (http://developer.android.com/reference/android/content/Intent.html) Intents provide a simple storage mechanism that can be retrieved and set, and are passed between two activities.

Use the GetExtra command to retrieve simple and complex objects from one activity to another using an Intent.

c06.indd 174c06.indd 174 28/07/12 6:01 PM28/07/12 6:01 PM

Building the Derby App in Android ” 175

You can select the extras you want to refer to individually from the Intent. For example:

String id = getIntent().getStringExtra(“id”); String name = getIntent().getStringExtra(“name”);

Or you can get all of the objects you passed along as a Bundle:

Bundle extras = getIntent().getExtras(); String userName; String id;

if (extras != null) { userName = extras.getString(“name”); id = extras.getString(“id”); }

Use the PutExtra command to put the object you want to pass between activities. You can pass simple or complex objects. You need to use Extras only when you want to pass data between activities. It is not necessary to set a complex state transfer process if you don’t need that data.

String username = “DerbyUser”; String id = “derbyuser42”; Intent newIdea = new Intent(this, newIdea.class); newIdea.putExtra(“username”, username); newIdea.putExtra(“id”, id); startActivity(newIdea);

Notifi cations You have lots of ways to display content to your users: either in your Base UI or through different types of notifi cations. What follows is an explanation of toasts and alerts.

Toasts A toast is a quick notifi cation that displays (by default) in a gray translucent box over your UI.

Context context = getApplicationContext(); //Find the application you are currently running CharSequence text = “Greetings from the App!”; //This is the message you want to share. int duration = Toast.LENGTH_SHORT; //This is a constant in the SDK for a quick notification Toast toast = Toast.makeText(context, text, duration); //Create the toast object toast.show(); //Display it for the duration now.

Alerts Simpler even than toasts, alerts are very similar to JavaScript alerts in that they pop a modal form with which you have very little ability to interact. You can set a button to represent affi rmation, declination, and cancellation alerts. The following snippet of code shows how to do that:

//Create a new AlertDialog using its builder respective to the current context. new AlertDialog.Builder(this)

c06.indd 175c06.indd 175 28/07/12 6:01 PM28/07/12 6:01 PM


.setTitle(“Alert Title”) //Set Title for the Alert

.setMessage(“Is this the message you expected?”) //Set Message for the alert

.setNegativeButton(“No”, null) //Set the Declination Button (Optional)

.setPositiveButton(“Yes”, null) //Set the Affirmation Button (Optional)

.setNeutralButton(“Who Cares”, null) //Set the Cancellation Button (Optional)

.show(); //Display the alert now.

Like all things in Android, you can customize notifi cations. You can fi nd more information on customizing them at http://developer.android.com/guide/topics/ui/notifiers/index.html.

O” ine Storage Even though the bulk of Android devices are smartphones — which afford users an always-on, always-connected experience — many reasons exist to store data on the device versus querying the a service remotely. For simple or small pieces of data you can use Shared Preferences; for larger data sets that may include complex objects, you can use SQLite.

SQLite SQLite is a fl at-fi le database that runs inside the Android framework. You can use it to store large object graphs or signifi cant amounts of data so that you aren’t constantly connecting to a remote source.

This is the base class for instantiating your SQLite instance in your Android app:

public class PersistingData extends Activity{ private static final String DATABASE_NAME = “DerbyData”; private SQLiteDatabase db; private DatabaseOpenHelper dbhelper;

/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ConnectToDatabase(this.getApplicationContext()); }

public void ConnectToDatabase(Context context){ dbhelper = new DatabaseOpenHelper(context, DATABASE_NAME, null, 1); }

public void DB_Open() throws SQLException{ db = dbhelper.getWritableDatabase(); }

public void DB_Close(){ if (db != null){ db.close(); } } }

This is a helper class to handle creating the database for you based on a predefi ned schema:

c06.indd 176c06.indd 176 28/07/12 6:01 PM28/07/12 6:01 PM

Building the Derby App in Android ” 177

public class DatabaseOpenHelper extends SQLiteOpenHelper{

public DatabaseOpenHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); }

@Override public void onCreate(SQLiteDatabase db) { String loadSchema = “CREATE TABLE DerbyNames” + “( DerbyNameId integer primary key autoincrement,” + “name TEXT, Number TEXT, League TEXT, DateAdded DateTime);”; db.execSQL(loadSchema); }

@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }

SharedPreferences SharedPreferences is a set of key-value pairs saved on your device that is helpful for storing instance-specifi c data as it pertains to the app. The main concern is the level of privacy that you impose upon it. If you make it world-readable its value can be accessed by any application should another application query against your key. This function is an example of leveraging SharedPreferences to store application preference for the user:

SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit();

public void savePreferenceToSharedPreferences(String key, String value){ editor.putString(key, value); editor.commit(); } public String loadPreferenceFromSharedPreferences(String key) { String tmpRtn = sharedPreferences.getString(key, “”); return tmpRtn; }

Web Service In Chapter 3 you developed a web service for the Derby application to call. This section goes over what you need to do to consume this information. In this example you write out the data to the log:

public class DerbyDataActivity extends Activity { /** Called when the activity is first created. */ @Override

c06.indd 177c06.indd 177 28/07/12 6:01 PM28/07/12 6:01 PM


public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); getLansingDerbyVixens(); }

In the following part you are loading up the activity, and telling it to run your getLansingDerbyVixens function.

public void getLansingDerbyVixens() { String requestURL = “http://derbynames.gravityworksdesign.com/DerbyNamesService.svc/ DerbyNames?$filter=League%20eq%20’Lansing%20Derby%20Vixens’”; Log.i(“DerbyData”, “getSurvey-Starting”); try { URL webRequest = new URL(requestURL); URLConnection tc = webRequest.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(tc. getInputStream()));

Log.i(“DerbyData”, “- before loading JSON”); StringBuilder surveyJSON = new StringBuilder(); String currentLine = “”; while ((currentLine = in.readLine()) != null) { surveyJSON.append(currentLine); }

This continuing function makes a webRequest to your service, takes the content of the response, and reads it in as a string. Because your service returns JSON you can deserialize each item in your JSON string to a DerbyName object using your getDerbyDataFromJSON function.

if (surveyJSON != null) { Log.i(“DerbyData”, “getSurvey-Have Data”); ArrayList<DerbyName> derbyNames = getDerbyDataFromJSON(surveyJSON.toString());

Next you iterate through the returned ArrayList<DerbyName> object and print each item’s properties in the log.

for(DerbyName item : derbyNames ){ Log.i(“DerbyData”, String.format(“Name=%s: Number=%s: League=%s”, item.getName(), item.getNumber(), item.getLeague())); } } } catch(Exception e) { Log.e(“DerbyData”, “Error getting data” + e.getMessage()); } Log.i(“DerbyData”, “finished”); }

c06.indd 178c06.indd 178 28/07/12 6:01 PM28/07/12 6:01 PM

Building the Derby App in Android ” 179

This function takes the JSON string and deserializes it into an ArrayList of DerbyName objects. You iterate through the contents of the returned objects and assign them to properties inside an instance of a DerbyName object, then add it to the ArrayList to be returned to your main function.

public static ArrayList<DerbyName> getDerbyDataFromJSON(String surveyDerby) { ArrayList<DerbyName> tmpRtn = new ArrayList<DerbyName>(); Log.i(“DerbyData”, “getDerbyDataFromJSON-Starting”); try { JSONObject fullJsonObject = new JSONObject(surveyDerby); JSONArray jsonNames = fullJsonObject.getJSONArray(“d”); // loop through each json derby name for (int i = 0; i < jsonNames.length(); i++) { DerbyName derbyName = new DerbyName(); JSONObject result = jsonNames.getJSONObject(i); derbyName.setDerbyNameId(result.getInt(“DerbyNameId”)); derbyName.setName(result.getString(“Name”)); derbyName.setNumber(result.getString(“Number”)); derbyName.setLeague(result.getString(“League”)); tmpRtn.add(derbyName); } } catch (JSONException e) { Log.e(“DerbyData”, “getDerbyDataFromJSON-Error converting JSON to Derby Name” + e.getMessage()); } Log.i(“DerbyData”, “getDerbyDataFromJSON-Finished”); // return return tmpRtn; }


The following class is the DerbyName object you have created to hold the data you get from the web service. You have effectively created an entity to equate to a single item from the service.

public class DerbyName { private int DerbyNameId; private String Name; private String Number; private String League; public int getDerbyNameId() { return DerbyNameId; } public void setDerbyNameId(int derbyNameId) {

c06.indd 179c06.indd 179 28/07/12 6:01 PM28/07/12 6:01 PM


DerbyNameId = derbyNameId; } public String getName() { return Name; } public void setName(String name) { Name = name; } public String getNumber() { return Number; } public void setNumber(String number) { Number = number; } public String getLeague() { return League; } public void setLeague(String league) { League = league; } }

Long-Running Tasks over the Web Please be aware that if you are going to be downloading a lot of data over any web request, or if you are in a high-latency situation, you might want to look into using the AsyncTask (http://developer.android.com/reference/android/ os/AsyncTask.html) for handling long-running tasks on a background thread. If your main thread hangs for roughly fi ve seconds, you can receive a message like the one shown Figure 6-23.

GPS The following function connects to your device’s GPS (if available) and displays a toast of your latitude and longitude when you go past its set threshold:

public class SensorsGPS extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

/* Use the LocationManager class to obtain GPS locations */ LocationManager locManager = (LocationManager) getSystemService(Context. LOCATION_SERVICE); LocationListener locListener = new MyLocationListener();

FIGURE 6!23: Common error when your Service times out

c06.indd 180c06.indd 180 28/07/12 6:01 PM28/07/12 6:01 PM

Building the Derby App in Android ” 181

locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener); }

/* Class My Location Listener */

public class MyLocationListener implements LocationListener { @Override public void onLocationChanged(Location loc) { loc.getLatitude(); loc.getLongitude();

String Text = “My current location is: “ + “\nLatitude = “ + loc.getLatitude() + “\nLongitude = “ + loc.getLongitude(); Toast.makeText(getApplicationContext(), Text, Toast.LENGTH_SHORT).show(); }

@Override public void onProviderDisabled(String provider) { Toast.makeText(getApplicationContext(), “GPS Disabled”, Toast.LENGTH_SHORT). show(); }

@Override public void onProviderEnabled(String provider) { Toast.makeText(getApplicationContext(), “GPS Enabled”, Toast.LENGTH_SHORT). show(); }

@Override public void onStatusChanged(String provider, int status, Bundle extras) {} }

Accelerometer In order to track motion and position of the Android device you will leverage the device’s built-in accelerometer as it monitors the x, y, and z axes of the device.

Following is a basic Activity that monitors the Accelerometer in your device:

public class SensorsAccel extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* do this in onCreate */ mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mSensorManager.registerListener(mSensorListener, mSensorManager. getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);

c06.indd 181c06.indd 181 28/07/12 6:01 PM28/07/12 6:01 PM


mAccel = 0.00f; mAccelCurrent = SensorManager.GRAVITY_EARTH; mAccelLast = SensorManager.GRAVITY_EARTH; }

private SensorManager mSensorManager; private float mAccel; // acceleration apart from gravity private float mAccelCurrent; // current acceleration including gravity private float mAccelLast; // last acceleration including gravity

private final SensorEventListener mSensorListener = new SensorEventListener() { public void onAccuracyChanged(Sensor sensor, int accuracy) {}

@Override public void onSensorChanged(SensorEvent se) { float x = se.values[0]; float y = se.values[1]; float z = se.values[2];

mAccelLast = mAccelCurrent; mAccelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z)); float delta = mAccelCurrent – mAccelLast; mAccel = mAccel * 0.9f + delta; // perform low-cut filter } };

@Override protected void onResume() { super.onResume(); mSensorManager.registerListener(mSensorListener, mSensorManager. getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); } @Override protected void onStop() { mSensorManager.unregisterListener(mSensorListener); super.onStop(); } }

SUMMARY This chapter outlined the best reasons to target Android as your framework. It covered how to get your development environment confi gured, gave you solid examples of best practices while developing your application and connecting with the Google Play, and fi nally how to implement the Derby application with all its respective functionality within Android.

Chapter 7 will cover these same topics using the iOS stack, for targeting iPhone, iPod touch, and iPad devices. Please note that development will require a computer running OSX.

c06.indd 182c06.indd 182 28/07/12 6:01 PM28/07/12 6:01 PM

Getting Started with iOS WHAT’S IN THIS CHAPTER?

! History of iOS

! Getting an iOS development setup

! Objective-C Basics

! iOS Project Basics

! Implementing the Derby App

This chapter is not intended to make you an expert iOS/Objective-C/Cocoa Touch developer; it’s intended to give you an idea of what it takes to create a mobile application on the iOS platform. In our everyday interaction with developers, we have found that many developers dread learning Objective-C, the native language used to create iOS applications. At technical conferences, we have often sat in on beginning-level sessions on how to develop iOS applications, where the presenter has said, “This is very diffi cult, you don’t want to do it.” We have no idea why some of the developer community thinks this way. Code is code (unless you are working with a functional language, but that’s a topic for a different day). Learning a new programming language/framework takes time and a bit of passion — if you are reading this book, we have no doubt in our mind that you can obtain some more Objective-C resources and have what you need to become an Objective-C developer.

THE IPHONE CRAZE The fi rst iPhone was revealed at the Mac World conference in early January 2007, and later released in June of that year. Initially, third-party native applications were not allowed. Apple executives argued that developers could build web (HTML/CSS) applications that would


c07.indd 183c07.indd 183 28/07/12 6:02 PM28/07/12 6:02 PM


behave like native iPhone apps. Developers pushed back, and in October 2007 Apple announced an SDK that allowed developers to create native iPhone applications. Many argue that Apple’s decision to allow developers to create native applications was based on the fact that the Android platform was going to be hitting the market soon, and was an extremely open and fl exible platform in which developers could do things that they could not within iOS. The decision to allow native apps within iOS created a new business model for developers, where small projects after work hours have turned into full-fl edged companies. As of February 2012, the Apple App Store contained more than 725,700 applications, which have collectively been downloaded more than 25 billion times.

Since June 2007, iPhones have helped drive the mobile boom. Apple converted a generation of iPod users to iPhone users with simple and effective user interface practices, and made its product “cool.” In May 2010, 59 percent of all mobile web data consumption in the U.S. came from iPhones. The iPhone was a game changer: a personal organizer, gaming platform, web browser, and a phone all in one small package.

Apple in Its Beauty When Steve Jobs introduced the world to the iPhone he proclaimed it as a revolutionary product that would change everything, with a brand-new “multi-touch” interface as breakthrough and as breathtaking as the mouse interface that was introduced in the 1960s. We agree with this statement, and feel that it was the iPhone that kick-started the mobile boom. The iPhone was marketed to consumers, and its ease of use made just about everybody want one.

At the time of its release, the core uniqueness of the iPhone went far beyond its web browser and tightly integrated web functionality. It was six core ideas (outlined in the following list) that changed software applications and websites. Although there were “smartphones” on the market at the time of release of the iPhone, it was not until after the iPhone was released that smartphone manufacturers realized the importance of all of these features being combined to provide a great mobile development platform.

Always on the Internet: A platform that had Internet access wherever cell phone coverage was available opened the door for a new type of application to be developed. Without this functionality, applications such as foursquare (an app that allows you to “check in” to locations) would not exist. This core concept is easy for developers to develop for; the most diffi cult part is coming up with an application idea.

Location-aware: The iPhone also introduced a platform that could detect where you were based on your location. Apart from privacy concerns, this feature has been well received in the developer and user community. Whether it’s a mapping application or an application that lets you tag photos with your location, this feature opened tremendous opportunity for developers to develop location-based apps that did not have to run on a standalone GPS.

Orientation-aware: In addition to location awareness, the iPhone offered a platform that could now detect where in space the device existed. The app that made this feature popular is Urbanspoon. Urbanspoon displays a random restaurant in your area based on criteria

c07.indd 184c07.indd 184 28/07/12 6:03 PM28/07/12 6:03 PM

that you set. If you do not like the restaurant that it picks, you can “shake” the phone and it will choose another one. This is a new type of UI feature that makes interfaces easier to use.

The mobile gaming industry has also taken full advantage of the iPhone’s orientation awareness, releasing many games that allow you use the device as the control stick; for example, moving the iPhone left and right in a race car game makes the car turn left and right, making it feel as though you are actually using a steering wheel.

Innovative input: The iPhone also represented a platform that could detect multiple fi ngers as input, as well as a wide range of gestures such as swipe up, swipe down, tap, dou- ble tap, and so on. With new input types, new UI patterns emerged helping make the small screen of the mobile device easier to deal with.

High-quality, scalable screen: A huge selling point for the iPhone is its high-resolution screen on which movies and photos can be viewed with stunning picture quality.

Power consciousness: Because the iPhone runs on battery, you as a developer need to watch the power consumption of your application. Loops within your code can cause the CPU to work hard, and when the CPU works hard it takes more power, causing your application to drain the device’s battery, which could result in negative comments from users. Years ago, developers worked to keep the size of applications small; for mobile development, you should pay close attention to how an application is coded, and ensure it doesn’t use too much power.

Apple Devices Throughout the years, Apple has produced many different types of mobile devices. From the iPod classic to the iPhone, Apple has created great products, but has not always opened these products up for developers to create apps for or modify them. For the purpose of this chapter, we are going to discuss iPhone, iPod touch, and the iPad. Although each of these devices runs a version of iOS, it’s important to note that older devices may not be able to run the latest version of iOS. For example, if your company tasked you with creating an app for your sales department and the entire sales team had iPhone 3Gs, you could not take advantage of the great features in iOS 5.0, because these devices run only in iOS 4.2.1 and below.

iPhone The iPhone may well be the reason why you are reading this book. Since its introduction in 2007, the iPhone has helped fuel the mobile boom that is currently underway. It has been the thorn in the side of many IT departments, from networking issues (employees bringing their own devices to work, which raises security concerns) to development issues (making your applications run on iOS). From 2007 to December 2011 fi ve devices have been released. It’s important to understand the close relationship between the iOS hardware and software. Meaning, not all versions of iOS will run on all iOS hardware. As device hardware becomes dated, Apple stops releasing iOS updates. Table 7-1 shows iOS hardware with the version of iOS that shipped with the device and the maximum version that can be installed on the device.

The iPhone Craze ” 185

c07.indd 185c07.indd 185 28/07/12 6:03 PM28/07/12 6:03 PM


TABLE 7!1 iPhone Hardware and iOS Versions


iPhone iOS 1.0 iOS 3.1.3

iPhone 3G iOS 2.0 iOS 4.2.1

iPhone 3GS iOS 3.0

iPhone 4 iOS 4.0

iPhone 4S iOS 5

iPod Touch After the release the original iPhone, Apple added a new product to the iPod product line: the iPod touch. This device was built on iPhone technology, looked identical to the iPhone, and used the same 480 ! 320 multitouch screen, but it was not a phone. This was a great option for consumers who wanted the iPhone experience, but did not want to pay the fees for a cell phone contract. Because of its lack of cellular connectivity, this device could access the Internet only through a wireless Internet connection. Table 7-2 shows iOS hardware with the version of iOS that shipped with the device and the maximum version that can be installed on the device.

TABLE 7!2 iPod touch Hardware and iOS Versions


1st generation iOS 1.1 iOS 3.1.3

2nd generation iOS 2.1.1 iOS 4.2.1

3rd generation iOS 3.1.1

4th generation iOS 4.1

iPad Introduced in January of 2010, the iPad was another revolutionary product from Apple. When the iPad was fi rst released, many argued it was just a big iPod touch, which was partially true. You could purchase a cellular data plan so that the device could access data but not phone service. The same great UI that made the iPhone and iPod Touch famous was now available with a 1024 ! 768 screen size.

The iPad pushed the mobile boom even more, with many industries seeing the benefi t that a tablet computer could provide. With two models containing different data storage sizes and access to cellular data, the iPad is leading the way in tablet computing. Table 7-3 shows iOS hardware with the version of iOS that shipped with the device and the maximum version that can be installed on the device.

c07.indd 186c07.indd 186 28/07/12 6:03 PM28/07/12 6:03 PM

Getting the Tools You Need ” 187

TABLE 7!3 iPad Hardware and iOS Versions


iPad iOS 3.2

iPad 2 iOS 4.3

iPad 3 iOS 5.1

GETTING THE TOOLS YOU NEED Developing for iOS is not a matter of opening up your favorite text editor and going to town. You may need to do a bit of planning, with the fi rst (and most expensive) being hardware. Depending on your development intentions you may need to pay Apple for the honor of being an iOS developer as well.

Hardware Oftentimes we are asked, “Do I really need to have a Mac?” The answer is yes. To develop iPhone, iPod, and iPad applications you must have a Mac. The iPhone SDK runs only on Mac OS X. The only sanctioned hardware for iPhone, iPod, and iPad development is an Intel-based Macintosh.

If you are having a hard time justifying the cost of the hardware, we have had great luck with getting refurbished machines direct from Apple at the following URL:


Because we work in many different languages and platforms each day, all of the developers we work with have Mac computers. The developers we work with mainly in .NET like to say the Macs are the best Windows machines they have ever had.

Program Levels If you do not have an Apple Developer account, you can create a free account at https:// developer.apple.com/. Having the Apple Developer account allows you to create iOS applications and run them locally on your machine using the iOS Simulator. To deploy applications you have created to a physical device (iPhone, iPad, iPod Touch) you must belong to the iOS Developer program. This is where the money comes in. These programs and prices change from time to time, so please use the following only as a guide, and check https://developer.apple.com/programs/start/ios/ before making any mission-critical decisions.

iOS Developer Program This program level allows developers to distribute apps in the App Store as an individual, a sole proprietor, a company, an organization, a government entity, or an educational institution. The cost for this program is $99 a year, and you are allowed to name 100 devices within your iOS Developer account (which is covered in the device section of this chapter).

c07.indd 187c07.indd 187 28/07/12 6:03 PM28/07/12 6:03 PM


iOS Developer Enterprise Program This program level allows developers to develop proprietary apps for internal distribution within your company, organization, government entity, or educational institution. The cost for this program is $299 a year. This level of the program will not allow you to distribute apps through the App store, but allows ad hoc distributions (distribute directly to a device without using the App Store) to devices in your organization. A valid Dun & Bradstreet (DUNS) number is required, and this program level will take a little bit longer to get enrolled in. We have seen this process take well over a month before acceptance into the program.

iOS Developer University Program This program level allows higher-education institutions to create teams of up to 200 developers that can develop iOS applications. This program level is free, and allows for programs to be tested on physical devices, but does not allow for ad hoc or App Store deployment.

The iOS Provisioning Portal No matter which level of Apple Developer program you registered for, you will have access to the iOS Provisioning Portal. This is the section of the iOS Developer Center that allows you to create the fi les necessary to deploy development and distribution (production) builds onto physical devices.

Certifi cates During the development process of your iOS app, you will more than likely create both a development and a distribution certifi cate. These certifi cates are used to digitally sign the app, and verify you are who you say you are. Figure 7-1 shows the iOS Provisioning Portal Certifi cate section, found within the iOS developer account web interface; here both development and distribution certifi cates are created.

FIGURE 7!1: iOS Provisioning Portal certifi cates

c07.indd 188c07.indd 188 28/07/12 6:03 PM28/07/12 6:03 PM

Getting the Tools You Need ” 189

App IDs Each iOS application that you create (that you intend to deploy to a device) needs to be identifi ed on the App IDs section of the iOS Provisioning Portal. The app ID that is created is a unique ID that contains a number from Apple and then a bundle identifi er that you specify. The bundle identifi er is usually in the format com.companyname.appname. As you start to develop more applications, they tend to become messy in this interface, as shown in Figure 7-2.

FIGURE 7!2: iOS Provisioning Portal App IDs

Devices The Devices section in the iOS Provisioning Portal section allows developers to maintain a list of devices in which their iOS applications will be developed. These are the devices that are either used for testing your app or for ad-hoc deployments. The number of devices that you can register on this screen relates to the type of Apple Developer account level you selected. For example, if you registered at the iOS Developer level, you will be able to add 100 devices. This number is 100 per year, meaning if you add 100 devices and then delete 10, you are still out of spaces for accounts until you re-enroll in the program the following year, which will still only have a maximum of 100 devices.

This can become problematic if you are developing iOS applications for multiple customers who have not set up accounts for themselves. It’s important to manage and plan ahead for the amount of devices you will need. Figure 7-3 shows that there is room for only 16 more devices in this account.

c07.indd 189c07.indd 189 28/07/12 6:03 PM28/07/12 6:03 PM


Provisioning Files After the certifi cate, the app ID, and devices have been created/added, you can then create a provi- sioning profi le. The provisioning profi le combines the information about which apps/certifi cates can be installed on which devices. As with certifi cates there will be a Development and Distribution version. Figure 7-4 shows the Provisioning section within the iOS Provisioning Portal.

FIGURE 7!3: iOS Provisioning Portal provisioning devices

FIGURE 7!4: iOS Provisioning Portal Provisioning Profi le

c07.indd 190c07.indd 190 28/07/12 6:03 PM28/07/12 6:03 PM

Getting the Tools You Need ” 191

FIGURE 7!5: iOS Dev Center

With all of the Apple administrative tasks complete with regard to setting up an account and obtaining provisioning profi les and certifi cates, you can move on to installing the xCode IDE and starting to work with the iOS SDK.

xCode and the iOS SDK To create native iOS applications, you will need to install both the xCode IDE as well as the iOS SDK. Although you can obtain xCode by using the App Store within Mac OS X, we recommend download- ing xCode and the SDK from the downloads section in the iOS Dev Center as shown in Figure 7-5.

Installation After you follow the steps to install xCode, you should have the xCode IDE as well as a great deal of other useful development tools installed to /Developer/Applications, as shown in Figure 7-6.

c07.indd 191c07.indd 191 28/07/12 6:03 PM28/07/12 6:03 PM


FIGURE 7!7: xCode startup screen

FIGURE 7!6: Development tools

You can start xCode from this directory or by using spotlight. After you start xCode, you should see a screen similar to the one shown in Figure 7-7.

Components of the iPhone SDK The iPhone SDK includes a great number of tools that help create iOS for apps. These tools range from debugging and profi ling to developing. This section lists the most common tools that we use that are included in the iOS SDK.

c07.indd 192c07.indd 192 28/07/12 6:03 PM28/07/12 6:03 PM

iOS Project ” 193

xCode xCode is Apple’s Integrated Development Environment (IDE) for creating Objective-C applications. xCode enables you to manage, author, and debug your Objective-C projects.

Dashcode Dashcode is an IDE that enables you to develop web-based iPhone/iPad applications and Dashboard widgets. This product is not in the scope of this book as it is considered an advanced topic.

iPhone Simulator This tool provides a method to simulate an iPhone or iPad device on your Mac, for use with testing your iOS applications.

Interface Builder The Interface Builder, or IB, is a visual editor that is used for designing the user interface for your iOS application.

Instruments Instruments is a suite of tools that helps you analyze your iOS application and monitor for performance bottlenecks as well as memory leaks in real time while attached to an iOS device or iOS Simulator.

The iOS Human Interface Guideline The iOS Human Interface Guideline (HIG) document is one of the most valuable tools to the iOS developer. The iOS HIG describes guidelines and principles that help the iOS developer design a superlative user interface and user experience. It is very important for new iOS developers to read through this document; if you do not develop using the UI principles found in the HIG, your application could be rejected when submitted to the Apple App Store.

The UI standards that Apple puts in place for developers can cause heated conversation. One side of the argument is that developers are locked into obeying a set of rules that cost time and money to learn and implement. The other side of the argument is that Apple has provided a standard UI for applications that have been created for the platform, thus giving the user a great experience no matter who creates the app.

You can fi nd the iOS HIG at http://developer.apple.com/library/ios/#documentation/ UserExperience/Conceptual/MobileHIG/Introduction/Introduction.html#/apple_ref/


With the xCode IDE and iOS SDK installed, you can now examine what exactly makes up an iOS project with respect to fi les and code.

IOS PROJECT By now you may be thinking that you need to follow a lot of steps before you start creating an iOS application. This may be the reason many seasoned iOS developers try to steer new developers from the platform. Although it takes a lot of steps to get going, they are not complicated or diffi cult; it’s just a matter of learning them and why they exist, which is covered in the remainder of this chapter.

c07.indd 193c07.indd 193 28/07/12 6:03 PM28/07/12 6:03 PM


With all of the “setup” out of the way, we can focus on getting into the IDE and looking at code.

Anatomy of an iOS App iOS .app fi les, the fi les that are actually deployed to the iOS device, are just a set of directories. Although there is an actual binary for the iOS application, you can open the .app fi le and fi nd the images, meta data, and any other resources that are included.

Views iPhone apps are made up of one or more views. Views usually have GUI elements such as text fi elds, labels, buttons, and so on. You can build a view built using the Interface Builder tool, which enables you to drag and drop controls on the view, or you can create a view entirely with code.

Code That Makes the Views Work Because iOS applications follow the MVC design pattern, there is a clean break between the UI and code that provides the application code.

Resources Every iOS application contains an icon fi le, an info.plist fi le that holds information about the application itself and the binary executable. Other resources such as images, sounds, and video are also classifi ed as resources.

Project Structure in Depth When an iOS project is created within xCode, the IDE creates a set of fi les that are ready to run. These fi les provide the basics of what is needed to get going with a new project. Figure 7-8 shows the fi les that are created for a new project named DeleteMe.

Main.m As with any C program, the execution of Objective-C applications start from the main() function, which is the main.m fi le.

AppDelegate.m The AppDelegate receives messages from the application object during the lifetime of your application. The AppDelegate is called from the operating system, and contains events such as the didFinishLaunchingWithOptions, which is an event that iOS would be interested in knowing about.

MainStoryBoard.storyboard This is where the user interface is created. In past versions of xCode/iOS the user interface was stored within .xib (pronounced NIB) fi les. Although this method is still supported, Storyboards are a great improvement over .xib fi les for applications with complex navigation and many views.

FIGURE 7!8: Anatomy of an iOS app

c07.indd 194c07.indd 194 28/07/12 6:03 PM28/07/12 6:03 PM

iOS Project ” 195

FIGURE 7!9: Project Navigator

Supporting Files The supporting fi les directory contains fi les such as the plist setting fi les (which contain customiz- able application settings), as well as string resource fi les that are used within your app.

Getting to Know the xCode IDE It’s important to use the correct tool for the job, regardless of whether you are constructing a house or constructing an application. If you are new to xCode, there will be a bit of a learning curve to becoming profi cient with the IDE, but xCode is a top-notch IDE with many features for you to discover.

Navigators The left side of the xCode window is known as the navigator area. A variety of navigators enable you to list the contents of your project, fi nd errors, search for code, and more. The remainder of this section introduces the Project Navigator, the Search Navigator, and the Issue Navigator.

Going from left to right, the project navigator is the fi rst of the xCode navigators; the icon looks like a fi le folder. The Project Navigator simply shows the contents of your project or workspace, as shown in Figure 7-9. Double-clicking a fi le in the Project Navigator opens the fi le in a new window, and single-clicking opens the fi le within the xCode workspace.

c07.indd 195c07.indd 195 28/07/12 6:03 PM28/07/12 6:03 PM


FIGURE 7!10: Search Navigator

The Issue Navigator lists project warnings and errors in real time as you make mistakes. This navi- gator shows any issues preventing your code from compiling, as shown in Figure 7-11.

The Search Navigator helps you locate text within your project or workspace as shown in Figure 7-10.

c07.indd 196c07.indd 196 28/07/12 6:03 PM28/07/12 6:03 PM

iOS Project ” 197

FIGURE 7!11: Issue Navigator

Storyboards In iOS versions prior to iOS 5, developers needed to create a separate XIB fi le for each view of their application. A XIB fi le is an XML representation of your controls and instance variables that get compiled into the application. Managing an application that contains more than a few views could get cumbersome.

iOS 5 contained a new feature called storyboards that enables developers to lay out their workfl ow using design tools built within xCode. Apps that use navigation and tab bars to transition between views are now much easier to manage, with a visual representation of how the app will fl ow. Transitions and segues are used to switch between views, without ever having to code them by hand.

c07.indd 197c07.indd 197 28/07/12 6:03 PM28/07/12 6:03 PM


With Storyboards, you will have a better conceptual overview of all the views in your app and the connections between them. Figure 7-12 is an example of a Storyboard for an application that contains a tab bar for navigation to three other views. Segues are the arrows that connect the views.

FIGURE 7!12: Sample Storyboard

c07.indd 198c07.indd 198 28/07/12 6:03 PM28/07/12 6:03 PM

Debugging iOS Apps ” 199

DEBUGGING IOS APPS A bug discovered in the fi eld is much more expensive to fi x than bugs that are found on a developer’s machine or during the quality assurance process. Modern-day IDEs provide a great deal of tooling that helps developers fi nd issues in their code before it reaches production.

The iOS Simulator Developers use the iOS Simulator as their fi rst way of fi nding issues with the code they just created. The iOS Simulator enables developers to run their iOS applications on their Macs without having to have a physical iOS device. The Simulator is a great tool for testing your apps quickly. The iOS Simulator is very quick to load, compared to other simulation tools for other mobile platforms. The iOS Simulator is also a great tool for HTML/CSS experts to have installed as well to test mobile webpages rendered within the mobile Safari web browser. Figures 7-13 and 7-14 show the Simulator simulating an iPhone and iPad, respectively.

The term “debugging” was made popular by Admiral Grace Murray Hopper, who was working on a Mark II computer at Harvard University in August 1945, when colleagues discovered a moth stuck in a relay that was causing issues with the system. She made the comment they were “debugging the system.”

FIGURE 7!13: iOS Simulator simulating an iPhone

FIGURE 7!14: iOS Simulator simulating an iPad

c07.indd 199c07.indd 199 28/07/12 6:03 PM28/07/12 6:03 PM


By no means is the Simulator the only tool you should use for testing your app. Although the Simulator is great for testing some things, it lacks in other areas. Not all applications that are avail- able on a physical iOS device are available within the Simulator. Besides that, memory, performance, accelerometer, and camera functionality cannot be tested reliably in the Simulator.

One nice feature of the iOS Simulator is the ability to test various iOS versions, as shown in Figure 7-15.

FIGURE 7!15: iOS Simulator version options

The iOS Simulator is not an emulator. An emulator tries to mimic the behavior of a real device. The iOS Simulator simulates real behavior of the iOS device, but relies on various libraries that are installed on the Mac, such as QuickTime, to perform renderings so that it looks like an actual iPhone. Applications that are deployed to the iOS Simulator are compiled to x86 code, whereas on a real iOS device the code would be compiled to ARM-based code.

Debugging Code As with many modern-day IDEs, Apple and the xCode team have put a great deal of time and effort into creating a set of tools to aid developers in their quest for hunting bugs.

When it boils down to it, developers want tools that make their life easier — tools to step through the code, view log messages, as well as see the state of their variables. xCode provides tools for these features, and much more.

c07.indd 200c07.indd 200 28/07/12 6:03 PM28/07/12 6:03 PM

Debugging iOS Apps ” 201

The debugging tools within xCode are located at the bottom of the workspace window. If you do not see the debugging tools, you can click View # Debug Area # Show Debug Area from the xCode menu (see Figure 7-16) to make the debugging tools visible.

FIGURE 7!16: The Debug area

Local Window When the debug area is enabled, the local window shows you a list of all of the variables that are currently within scope of your current breakpoint, and enables you to view details about each vari- able. Figure 7-17 shows the local window, and you can see that an object named derbyNameDetail that is of type NSCFArray contains 908 elements within the array.

FIGURE 7!17: The local window

c07.indd 201c07.indd 201 28/07/12 6:03 PM28/07/12 6:03 PM


Breakpoints You can set breakpoints by clicking on the “gutter” next to the line of code where you would like the application to break. Breakpoints can be enabled and disabled; disabled breakpoints have an opaque blue color, whereas active breakpoints are a solid blue, as shown in Figure 7-18.

FIGURE 7!18: Breakpoints added to the gutter

The top of the debug area contains the Breakpoint toolbar, with tools that enable you to Step Over, Step Into, Step Out, and continue execution of your code. These tools are located in the Debug Area’s toolbar, as shown in Figure 7-19.

FIGURE 7!19: Breakpoint toolbar

Output The output section of the Debug Area gives important information about the execution of the app, as well as displays any log messages you may add in your code. Figure 7-20 shows the application output of an application that logged information received from a web service.

c07.indd 202c07.indd 202 28/07/12 6:03 PM28/07/12 6:03 PM

Debugging iOS Apps ” 203

Call Stack When hunting for bugs, it’s useful to follow the execution path of a particular feature, in hopes of fi nding the issue. Figure 7-21 shows the stack trace window within xCode.

FIGURE 7!20: Output window

FIGURE 7!21: The call stack window

c07.indd 203c07.indd 203 28/07/12 6:03 PM28/07/12 6:03 PM


Instruments Suppose you’ve spent the last few weeks working nights to get a version of an iOS app ready for release, but after you use your application for about 15 minutes, it stops for no reason. You think it may be a memory leak of some kind, but are not completely sure because the log messages were pretty cryptic. Instruments is the tool for you. Instruments can be found in the Developer # Application directory. Tools within the Instruments tool suite enable you to track down memory issues and help fi nd slow-running code. Instruments is one of our favorite tools found within xCode, because it helps us fi nd those hard-to-replicate issues. Figure 7-22 shows a few of the trace templates that are available for iOS.

FIGURE 7!22: Instruments analysis tools

OBJECTIVE!C BASICS Objective-C is an object-oriented language based on the C programming language. Objective-C adds Smalltalk-style messaging, which throws even the seasoned polyglot programmer for a loop when starting with this language. Objective-C was created in the early 1980s by Brad Cox and Tom Love, and gained popularity when Steve Jobs and NeXT licensed the language from them, and made Objective-C the main language on NeXT’s NextSTEP operating system.

c07.indd 204c07.indd 204 28/07/12 6:03 PM28/07/12 6:03 PM

Objective-C Basics ” 205

Objective-C requires developers to declare a class in an interface and then defi ne the implementation, something that non-C developers fi nd off-putting about the language. If you are comfortable developing in C languages, Table 7-4 will help you fi nd your bearings when getting started with Objective-C.

TABLE 7!4: Equivalencies between C languages and Objective-C


#include “library.h” #import “library.h”

this self

private: @private

protected: @protected

public: @public

Y = new MyClass(); Y = [[MyClass alloc] init];

try, throw, catch,!fi nally @try, @throw, @catch, @fi nally

Classes The interface of Objective-C classes is defi ned in a header fi le for each interface. Usually the fi lenames of the header match the class name. For example, you can create a header fi le named dog.h:

@interface Dog : Animal { // instance variables }

// Method declarations


You are telling the compiler that a new class named Dog, which is a subclass of animal, is being declared. Any instance variables are declared between the curly brackets, and methods are declared between the end of the curly bracket and the @end keyword.

The actual implementation of the Dog class would look like this:

#import “dog.h” @implementation Dog // method definitions @end

c07.indd 205c07.indd 205 28/07/12 6:03 PM28/07/12 6:03 PM


Instance Variables The attributes that are declared between the curly brackets are instance variables. Instance variables are declared like local or global variables, but have a different scope. Instance variables by default are visible in all instance methods of a class and its subclasses.

Methods Methods can be declared as either instance methods or class methods. Instance methods are called by sending a message directly to the instance of the class, which means you need to have your own instance of the class before you can call these methods. Instance methods are prefi xed with a minus sign (-). The following is an example of the declaration for an instance method that returns the name of the animal, and takes no parameters:

-(NSString) getNameOfAnimal;

A class method does not require an instance of a class. You call a class method by sending a message to the unique class object. C# or Java developers may recognize class methods as static methods. The following method returns an array containing a list of all nonextinct animals:

+(NSArray) getNonExtinct();

Calling Methods You may have noticed that Objective-C is heavy on the use the brackets. In Objective-C, methods are not called in the traditional sense; their objects are sent messages. The syntax for sending messages is to enclose the name of the object and the message with square brackets:

[object method]; [object methodWithInput:input];

Methods can return values:

output = [object methodWithOutput]; output = [object methodWithInputAndOutput:input];

Objective-C 2.0 provides a dot-notation that can be used to invoke methods. Many new Objective-C developers like this syntax because it looks like other languages in which they are more profi cient.

Implementation in Non-Dot Notation:

int lastLocation = [myAnimal getLastLocation];

Implementation in Dot Notation:

int lastLocation = myAnimal.getLastLocation;

Control Structures Oftentimes when learning a new language, we like to look at the control structures to get an idea of how to implement these types of structures.

c07.indd 206c07.indd 206 28/07/12 6:03 PM28/07/12 6:03 PM

Objective-C Basics ” 207

If Statements If statements are pretty straightforward in Objective-C. The following example checks to see if an array of animal names contains a name “luna”:

NSArray *animalNames = … NSString* nameOne = @”luna”;

if ( [animalNames containsObject: nameOne] ) { … } else { // do something else }

For Loops The standard C for loop can be used to iterate over an enumerable object such as an array in Objective-C. The following example loops over an array of animal objects and prints their location to the console screen:

NSArray *animals = … NSUInteger animalCount = [animals count];

for (j=0; j < animalCount; j++ ) { NSLog([[animals objectAtIndex: j] getLastLocation]); }

Fast Enumeration Objective-C 2.0 also gives us new syntax for a control structure called Fast Enumeration. Fast Enumeration is easier for developers to code, and runs faster than other traditional loops such as for and while loops.

NSMutableArray *animals = …

for (Animal *singleAnimalObject in animals ) { NSLog([singleAnimalObject getLastLocation]); }

Try Catch Error handling is one of those developer religious debates that we are not going to get into in this chapter. We will tell you that exception handling in Objective-C is expensive, and was designed for catching programmer errors or other nonrecoverable problems. If you can test for an error condition in advance, you should do so rather than catching exceptions. Your code will run must faster.

c07.indd 207c07.indd 207 28/07/12 6:03 PM28/07/12 6:03 PM


The following example illustrates the structure of exception handling in Objective-C:

@try { // code that may cause the exception } @catch (NSException *e) { //exception is caught and logic should be added to handle the exception } @finally { // code that should be executed no matter if an exception has occurred or not. }

Now that the Objective-C basics are covered, you can dive in and create your fi rst native iOS app with Objective-C and the iOS SDK.

HELLO WORLD APP Before you can run, you need to walk. We are not huge fans of creating Hello World–type apps, but with the iOS SDK and Objective-C so different from many other application frameworks, we felt it made sense.

This section illustrates the steps needed to create a simple iOS application that contains a label and a button. When the button is touched, the text in the label changes. This allows us to explain xCode and the various tools contained within xCode that are required when making an iOS application.

Creating the Project After opening xCode, create a Single View Application project type found under the iOS project types, as shown in Figure 7-23. When you select a Single View Application, xCode generates the fi les you need to start creating an iOS app that has only one view.

FIGURE 7!23: iOS project template

c07.indd 208c07.indd 208 28/07/12 6:03 PM28/07/12 6:03 PM

Hello World App ” 209

After you select a project template, you are prompted to enter the project level options as shown in Figure 7-24.

FIGURE 7!24: iOS project options

For this example, enter a product name of Hello World, target the iPhone, set the company identifi er to whatever you choose, and leave the default settings for the rest.

Product Name xCode uses the product name you enter to name your project and the application. If you want your application name to show up differently in iOS, there is an option in the .plist fi le to set the display name of the app.

Company Identifi er This identifi er is used to generate the bundle identifi er for the iOS app. The company identifi er is usually something like com.gravityworksdesign.

Bundle Identifi er The bundle identifi er is automatically generated for you and is a combination of the product name and company identifi er. This identifi er is used when provisioning your app to be installed on devices. The bundle identifi er is unique to an app, and the Apple developer tools will not allow you to provi- sion an app when an existing app is using the same bundle identifi er.

Class Prefi x The text you enter into the Class Prefi x fi eld is prefi xed to the fi lenames and class names of all header and implementation fi les.

c07.indd 209c07.indd 209 28/07/12 6:03 PM28/07/12 6:03 PM


Device Family This option enables you to target which type of device your application will run on: iPhone, iPad, or Universal. Universal allows your application to be run on both iPhone and iPad. Beneath Device Family are three checkboxes:

! Use Storyboard: As mentioned previously in this chapter, Storyboards are new to iOS 5. They are a great feature to aid in iOS development, but some developers are stuck in their ways, and may not like Storyboards (or may have some other valid reason). This option creates .xib fi les for each view just like previous versions of the iOS SDK/xCode.

! Use Automatic Reference Counting: A new feature to iOS 5, automatic reference counting manages memory so that developers do not have to do it themselves. Automatic reference counting can be considered a type of garbage collection mechanism. If you are creating an application that needs to be deployed on versions of iOS less than 5, automatic reference counting is not supported, so this option must be disabled.

! Include Unit Tests: When this option is checked, xCode generates the fi le structure for a set of unit tests for your iOS application. It is your responsibility to create and maintain these unit tests.

After the project has been created, you will see a screen similar to Figure 7-25. This screen contains the project level options for your app. On this screen, you can add a launch image (splash screen), the app icon, target-specifi c device orientations, target-specifi c versions of iOS, and the list goes on and on.

FIGURE 7!25: iOS Project screen

c07.indd 210c07.indd 210 28/07/12 6:03 PM28/07/12 6:03 PM

Hello World App ” 211

You do not have to do anything on this screen for the Hello World app.

Creating the User Interface The user interface is fairly simple for this app. It has a label and a button. We are not going to get fancy with any UI elements, but feel free to explore and extend the application to get a feel of your fi rst iOS app.

Controls in the View From the Project Navigator, select the MainStoryboad.storyboard fi le. You then need to put a label control on the view. You can fi nd the controls that you have access to on the bottom right of the IDE in the Object Library. Find the label control, and drag the control to the storyboard. Your app should look similar to Figure 7-26 now.

FIGURE 7!26: Hello World Storyboard

When you click the label in the storyboard, you should see settings that are specifi c to that control in the upper-right side of xCode in the Identity Inspector. The Identity Inspector is a settings tool, which enables you to control font color, size, and other options specifi c to the control you are working with. Figure 7-27 shows the Identity Inspector interface when editing the settings for a button.

c07.indd 211c07.indd 211 28/07/12 6:03 PM28/07/12 6:03 PM


The next step is to add a button to the view. Buttons are added like the label control, by dragging the control onto the view. In this example set the button text to say Change Label.

Wiring Up the Controls By this point you should have a view that contains two controls: a label and a button. If you run your application, you should see the interface you developed in the iOS Simulator, but you have not told the applica- tion to do anything yet. Wiring up the controls to events can be tricky for new developers on this platform.

The fi rst thing you want to do is to show the Assistant Editor. You can toggle this editor on and off by selecting the “Tuxedo” button near the upper-right side of the IDE, as shown in Figure 7-28.

Depending on where you have the Assistant Editor set to show, yours may be placed differently than the following screenshots. To change where exactly on the screen the Assistant Editor shows, you can select View # Assistant Editor from the xCode menu and then select where you would like the editor to show.

Defi ning the Label The next step is a bit tricky. You need to defi ne your controls in the header fi le. To do this, hold down the Control key on the keyboard, and click and drag your label control from the storyboard to the header fi le that is shown in the Assistant Editor (see Figure 7-29).

FIGURE 7!27: xCode control-specifi c settings

FIGURE 7!28: Toggling the Assistant Editor

FIGURE 7!29: Defi ning controls

c07.indd 212c07.indd 212 28/07/12 6:03 PM28/07/12 6:03 PM

Hello World App ” 213

Once you release the mouse, a dialog box appears asking you to name the object. We like to follow Hungarian notation for control names, so name the label lblChangeMe as shown in Figure 7-30.

Wiring the Button Wiring the event for the button is similar to defi ning the event. If you right-click the button you see a dialog box similar to the one shown in Figure 7-31.

You are most interested in the Touch Up Inside event, which is the event that occurs when a fi nger is raised off the control. This is where you want to add logic . To do this, simply click the circle next to the Touch Up Inside event, and drag it to the Assistant Editor as shown in Figure 7-32. As with the label, you are prompted for a name; name this one btnChangeText_click.

FIGURE 7!30: Naming the control

FIGURE 7!31: Right-clicking a control

FIGURE 7!32: Defi ning the Touch event

c07.indd 213c07.indd 213 28/07/12 6:03 PM28/07/12 6:03 PM


Like all Hello World–type apps, the intention was to give you an idea of the project structure and basic interaction between the UI and code. To build upon this, the next section tackles a more complex native iOS app.

BUILDING THE DERBY APP IN IOS The idea of the Derby App is to build the same app over all of the mobile platforms covered in this book. The iOS version is very similar to the other versions that you have built thus far or will build in future chapters.

Writing the Code With the UI completed and wired up, you can now tell your app what you want the Touch event to do when touched. To do this, open the ViewController.m fi le, and add the following method:

– (IBAction)btnChangeText_click:(id)sender { NSString* newText = @”My new text”; lblChangeMe.text = newText; NSLog(newText); }

This code defi nes a new string, sets the label text to the new string, and then logs the new string to the event viewer. If you followed the steps correctly, your app should look similar to Figure 7-33 in your iOS Simulator, and you should see a log fi le similar to Figure 7-34 in the output window of xCode.

FIGURE 7!33: Completed Hello World iOS app FIGURE 7!34: Output of the Hello World app

c07.indd 214c07.indd 214 28/07/12 6:03 PM28/07/12 6:03 PM

Building the Derby App in iOS ” 215

The requirements are to list the roster from the Lansing Derby Vixens roller derby team as the primary function, and then list all the roller derby teams in the world with the ability to see their team rosters.

User Interface The derby app contains a list of data, so you use table views throughout the application to show the information to the user. Start by creating a new tabbed application within xCode as shown in Figure 7-35.

FIGURE 7!35: Creating a tabbed app

By default xCode creates a new iOS application that contains a Storyboard with tabbed navigation. Your project needs to contain three table views and one Navigation controller. The table views are used to the list the data about the derby teams and rosters, and the navigation controller enables you to create a “back stack” that will allow users to navigate back to the team names table view, when fi nished viewing the team’s roster data. Start by dragging three Table View Controllers from the Object Library onto the storyboard, and then remove the views that were added by default.

Once the previous views are removed and the table views are added, you need to connect them to the navigation controller. To do this, Control-click the Tab Bar Controller icon on the Tab Bar View, within the Storyboard, and drag it to the new view as shown in Figure 7-36.

c07.indd 215c07.indd 215 28/07/12 6:03 PM28/07/12 6:03 PM


When prompted, select Relationship for the type of Storyboard segue from the dialog box shown in Figure 7-37. This adds a new icon to the Tab Bar Controller for the Table View that was just linked.

Setting the segues for the remainder of the storyboard is very similar. Use the Control-drag functionality to link the main Tab Bar Controller to the Navigation Controller, then link the Navigation Controller to the League Table View, and the League Table View to the Details Table View as shown in Figure 7-38.

FIGURE 7!36: Connecting view to tab bar

FIGURE 7!37: Selecting relationship for segue

FIGURE 7!38: Linking the Navigation Controller for the leagues

c07.indd 216c07.indd 216 28/07/12 6:03 PM28/07/12 6:03 PM

Building the Derby App in iOS ” 217

The segue that is created from the Leagues view needs to have an identifi er of “Details.” This enables you to trigger this particular segue from within code. To do this, click the segue (the arrow between the Leagues Table View and the Details Table View), and open the Identity Inspector. In the Identifi er box enter Details as shown in Figure 7-39.

When you have completed this task, you should have a storyboard that looks similar to Figure 7-40. For complete code samples, visit this book’s page on http://www.wrox.com and click the Download Code tab.

FIGURE 7!39: Adding an identifi er to a segue

FIGURE 7!40: Relationships completed

Team Roster With the storyboard in place, you can now write the code to populate the table views. Start with the Team Roster tab, which will go out to a web service, and obtain a list of all the Lansing Derby Vixens.

c07.indd 217c07.indd 217 28/07/12 6:03 PM28/07/12 6:03 PM


First create a new class named VixensViewController:

@interface VixensViewController : UITableViewController @property(nonatomic, retain) NSArray *listData; @end

In the viewDidLoad method within the implementation fi le, add your logic to go out the web service and get the roster for the Lansing Derby Vixens. Notice the fi lter criteria contained within the URL.

– (void)viewDidLoad { [super viewDidLoad]; NSMutableArray *array = [[NSMutableArray alloc] init]; // go out to the service and get the data NSError *error = nil; NSURL *derbyService = [NSURL URLWithString: @”http://derbynames.gravityworksdesign.com/DerbyNamesService.svc/ DerbyNames?$filter=League%20eq%20’Lansing%20Derby%20Vixens’”]; NSData *data = [NSData dataWithContentsOfURL:derbyService];

// Use native functions to parse the JSON NSDictionary *derbyNames = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error]; NSArray* derbyNameDetail = [derbyNames objectForKey:@”d”]; // loop through all of the derby objects only add the name object to the array for (NSDictionary* derbyItem in derbyNameDetail) { NSString *name = [derbyItem objectForKey:@”Name”]; NSString *league = [derbyItem objectForKey:@”League”]; NSString *number = [derbyItem objectForKey:@”Number”]; NSLog(@”Names: %@-%@-%@”, name, league, number); [array addObject:name]; }

self.listData = array; }

iOS 5 is the fi rst version of the iOS SDK that contains built-in support for parsing JSON strings. This is great because you do not have to depend on a third-party tool. The last line in the method self.listData = array; sets the data that you will use to bind the data to the table view.

For the table view to know how many rows it needs to select, you must implement the numberOfRowsInSection method. In this case, just return the count of the number of items in the listData array, which is the array that you populated when the view loaded.

c07.indd 218c07.indd 218 28/07/12 6:03 PM28/07/12 6:03 PM

Building the Derby App in iOS ” 219

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.listData count]; }

The magic really happens in the cellForRowAtIndexPath method. This method is called for the number of times that was returned in the numberOfRowsInSection. In the code, you create a new cell, get the data for the correct position in the listData array, and then return the cell you created, which will be added to the table:

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @”Cell”; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } // Configure the cell… NSUInteger row = [indexPath row]; cell.textLabel.text = [listData objectAtIndex:row]; return cell; }

Details The next class you need to create is DetailViewController. This is the code that drives the details that are displayed when a team name is selected.

#import <UIKit/UIKit.h>

@interface DetailViewController : UITableViewController

@property (nonatomic, retain) NSString *data; @property(nonatomic, retain) NSArray *listData;


The logic for this is very similar to what you just implemented for the roster view, but you are adding a new string named data, which holds the string value of the team for which you want to receive the roster. This string is passed into this view, allowing you to fi lter which roster is shown. You need to implement both the numberOfRowsInSection and cellForRowAtIndexPath methods exactly as you did with the roster view.

You can see that the viewDidLoad code is very similar, but you take the data string, encode it for URL use, and then append it to your URL that fi lters which team to get the roster for:

c07.indd 219c07.indd 219 28/07/12 6:03 PM28/07/12 6:03 PM


– (void)viewDidLoad { [super viewDidLoad]; // build our URL to get the data from NSString* url = @”http://derbynames.gravityworksdesign.com/DerbyNamesService.svc/ DerbyNames?$filter=League%20eq%20’”; NSString* escapedUrlString = [data stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding]; NSString *urlToGetData = [NSString stringWithFormat:@”%@%@’”, url,escapedUrlString]; // get the data NSMutableArray *array = [[NSMutableArray alloc] init]; NSError *error = nil; NSURL *derbyService = [NSURL URLWithString: urlToGetData]; NSData *rosterData = [NSData dataWithContentsOfURL:derbyService]; NSDictionary *derbyNames = [NSJSONSerialization JSONObjectWithData:rosterData options:NSJSONReadingMutableLeaves error:&error]; // process the data NSArray* derbyNameDetail = [derbyNames objectForKey:@”d”]; for (NSDictionary* derbyItem in derbyNameDetail) { NSString *name = [derbyItem objectForKey:@”Name”]; NSString *league = [derbyItem objectForKey:@”League”]; NSString *number = [derbyItem objectForKey:@”Number”]; NSLog(@”Names: %@-%@-%@”, name, league, number); [array addObject:name]; } // return the data self.listData = array; }

Leagues and Team Names Listing all of the team names is very similar to the code you just created for displaying the roster and the details. Start by creating a new class named LeagueTableViewController:

#import <UIKit/UIKit.h>

@interface LeagueTableViewController : UITableViewController @property(nonatomic, retain) NSArray *listData; @end

The viewDidLoad method will look very similar, but notice the URL you are using this time, which is different from the previous URL. This URL returns a JSON string containing the team names.

c07.indd 220c07.indd 220 28/07/12 6:03 PM28/07/12 6:03 PM

Building the Derby App in iOS ” 221

– (void)viewDidLoad { [super viewDidLoad];

NSMutableArray *array = [[NSMutableArray alloc] init];

// go out to the service and get the data NSError *error = nil; NSURL *derbyService = [NSURL URLWithString: @”http://derbynames.gravityworksdesign.com/ DerbyNamesService.svc/Leagues”]; NSData *data = [NSData dataWithContentsOfURL:derbyService]; // Use native functions to parse the JSON NSDictionary *derbyNames = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error]; // loop through the derby objects returned only add the name object to the array NSArray* derbyNameDetail = [derbyNames objectForKey:@”d”]; for (NSDictionary* derbyItem in derbyNameDetail) { NSString *name = [derbyItem objectForKey:@”LeagueName”]; NSLog(@”Names: %@”, name); [array addObject:name]; } self.listData = array; }

What’s new in this view is the functionality to select a row. When the row is selected, a new view that contains the list of team members for that derby team is opened. To accomplish this you fi rst need to implement the didSelectRowAtIndexPath method. In your method you get the cell and then call the performSegueWithIdentifier method.

– (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath]; [self performSegueWithIdentifier:@”Details” sender:cell]; }

After the user selects the table row, you need to pass the data in the cell that the user touched to the details view, which will show the roster for that particular team. The performSeagueWithIdenti- fier method is the code that actually switches the views for you. In this case, you are following a segue with the name of Details. Before the transfer is performed, you set the destination controller of the segue to a new DetailViewController and set the data property on the detail view to the contents of the cell, in this case the name of the derby team for which you want to see the roster.

c07.indd 221c07.indd 221 28/07/12 6:03 PM28/07/12 6:03 PM


– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:@”Details”]) { DetailViewController *detailView = segue.destinationViewController; UITableViewCell *dataCell = (UITableViewCell *)sender; [detailView setData:dataCell.textLabel.text]; } }

After all of the code has been added to the new View Controllers you created, you need to go back to the Storyboard and attach them as shown in Figure 7-41. You do this using the Identity Inspector found near the upper right of the screen when you are viewing the storyboard. Map each view to the correct class that was created.

With this logic in place, you should now have a working Derby App created natively with iOS. Your app should look similar to Figure 7-42.

FIGURE 7!41: Attaching a class to a View

FIGURE 7!42: Completed Derby application

This section of the iOS chapter covered creating a native iOS mobile app using xCode and Objective-C. The Derby app example covers the major functionality that a mobile developer would encounter when creating an app, such as creating UI and communicating with an external data service. By no means does this section give complete coverage as to what it takes to be an iOS developer, but it should lead you in the right direction.

c07.indd 222c07.indd 222 28/07/12 6:03 PM28/07/12 6:03 PM

Other Useful iOS Things ” 223

OTHER USEFUL IOS THINGS The two example projects up to this point have provided the basics for creating iOS applications that will go out to a web service and render the collected data on the screen. By no means do we feel that we have covered every possible situation you may need to develop a solution for, so we wanted to fi nish this chapter by providing a few more short examples that will help you out when discovering how the iOS framework works.

O” ine Storage Even if your application is using a web service for retrieving information, at some point you may need to save information on the device. Depending on the size and type of data, you have a few different options.

Plist Property lists are the simplest way to store information on the device. In the Mac world, many applications use the plist format to store application settings, information about the application, and even serialized objects. It’s best to keep the data contained in these fi les simple and small, though.

The following example fi nds the path to a plist stored in the supporting fi les directory, with a name of example. It then loads the plist into a dictionary object, and loops through each time writing the contents of each item in the plist to the debug console.

– (void)getValuesFromPlist { // build the path to your plist NSString *path = [[NSBundle mainBundle] pathForResource: @”example” ofType:@”plist”]; // load the plist into a dictionary NSDictionary *pListData = [[NSDictionary alloc] initWithContentsOfFile:path]; // loop through each of the Items in the property list and log for (NSString *item in pListData) NSLog(@”Value=%@”, item); }

If you want to get a single item out of the plist the code is very similar. The following example cre- ates a function named outputSinglePlistValue that takes in the name of the item you want to output, itemName. You then just use the objectForKey method to get the value of a specifi c key in the dictionary that was returned.

– (void)outputSinglePlistValue: (NSString*) itemName { // build the path to your plist NSString *path = [[NSBundle mainBundle] pathForResource:

c07.indd 223c07.indd 223 28/07/12 6:03 PM28/07/12 6:03 PM


@”example” ofType:@”plist”]; // load the plist into a dictionary NSDictionary *pListData = [[NSDictionary alloc] initWithContentsOfFile:path]; NSString *value = [pListData objectForKey:itemName]; NSLog(@”Name=%@-Value=%@”, itemName,value); }

To write to the plist fi le, again you need to load the plist into a dictionary, this time a mutable dictionary that will allow you to make changes. You can use the setValue method to change the value of a key, and then write the plist database to a fi le named example.

– (void)writeToPlist { NSString *path = [[NSBundle mainBundle] pathForResource: @”example” ofType:@”plist”];

NSMutableDictionary* pListData = [[NSMutableDictionary alloc] initWithContentsOfFile:path];

[pListData setValue:@”Modified Value” forKey:@”Test1”]; [pListData writeToFile:path atomically: YES]; }

Core Data If the data that you need to persist on the device is nontrivial, meaning there is a great deal of it or its complex, Core Data is the way to go. Core Data is described by Apple as a “schema-driven object graph management and persistence framework.” Core Data is not an ORM (Object Relational Mapper). Core Data is an API that abstracts the actual data store of the objects. Core Data can be confi gured to store these objects as a SQLite database, a plist, custom data, or a binary fi le. Core Data has a steep learning curve, but is well worth learning more about if your app will have a great deal of data held within.

GPS One of the great benefi ts to mobile devices is the GPS functionality. Once you are able to get over the hurdles of learning the basic functions within the iOS platform, starting to work with the GPS functions can be a great deal of fun.

The GPS functions are located in the CoreLocation framework, which is not added to a new proj- ect by default. To do this, you will need to click the Build Phases tab on the project settings page as shown in Figure 7-43.

c07.indd 224c07.indd 224 28/07/12 6:03 PM28/07/12 6:03 PM

Other Useful iOS Things ” 225

Once on the Build Phases tab, expand the Link Binary With Libraries section, and click the + button. You are then prompted with a list of frameworks to add. Select the CoreLocation.framework as shown in Figure 7-44.

FIGURE 7!43 Build Phases tab

FIGURE 7!44: Adding the CoreLocation framework

c07.indd 225c07.indd 225 28/07/12 6:03 PM28/07/12 6:03 PM


With the reference to the CoreLocation framework in place, you are now ready to start working with the GPS functionality. Start with the ViewController.h fi le. The CLLocationManager class will send out updates anytime the location is changed. These updates are sent out using the delegate pattern, which simply means your view controller needs to implement the CLLocationManagerDelegate protocol.

@interface ViewController : UIViewController <CLLocationManagerDelegate>{ CLLocationManager *locationManager; }

Once your header fi le implements the correct delegate, you can initialize the location manager in the ViewDidLoad method of the ViewController.h fi le. When you initialize this class, you have control over how frequently you want to receive updates as well as how accurately you want them.

// GPS Example locationManager = [[CLLocationManager alloc] init]; locationManager.delegate = self; locationManager.distanceFilter = kCLDistanceFilterNone; // get GPS DatalocationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; [locationManager startUpdatingLocation];

The last step you need to perform is to implement the method that is called whenever the location has changed. In this method you convert the raw GPS data that is sent from iOS to the common format of Degrees, Minutes, and Seconds, and then log the latitude and longitude:

– (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { // turn the raw lat info into degrees, minutes, seconds int latDegrees = newLocation.coordinate.latitude; double latDecimal = fabs(newLocation.coordinate.latitude – latDegrees); int latMinutes = latDecimal * 60; double latSeconds = latDecimal * 3600 – latMinutes * 60; NSString *latitude = [NSString stringWithFormat:@”%d° %d’ %1.4f\””, latDegrees, latMinutes, latSeconds]; NSLog(latitude); // turn the raw long into degrees, minutes, seconds int longDegrees = newLocation.coordinate.longitude; double longdecimal = fabs(newLocation.coordinate.longitude – longDegrees); int longMinutes = longdecimal * 60; double longSeconds = longdecimal * 3600 – longMinutes * 60; NSString *longitude = [NSString stringWithFormat:@”%d° %d’ %1.4f\””, longDegrees, longMinutes, longSeconds]; NSLog(longitude); }

c07.indd 226c07.indd 226 28/07/12 6:03 PM28/07/12 6:03 PM

Summary ” 227

When you run this example project you are prompted from iOS whether you want to allow this application to use your current location, as shown in Figure 7-45. The Simulator will return the GPS location for Cupertino, California. So if you are looking for more accurate data, you will need to deploy the app to a physical iOS device.

SUMMARY This chapter spent a great deal of time describing the iOS platform. After reading this chapter, you should be comfortable installing xCode and getting started developing and debugging your fi rst iOS app. Developing for iOS should not be rushed into. Even though corporate executives are pushing development teams to create applications for the iOS platform, you should take a step back and make sure it really makes sense.

Apple has helped push the world into the mobile boom that we are in now, and it is constantly innovating and pushing the mobile industry. Choosing one platform helps developers focus their skills, but locks them into that platform. Apple is known for not being kind to developers, by providing tools that are not the easiest to work with. However iOS fi ts into your strategy, be aware that Apple has a large market share, and will be around for a long time.

The following chapter will take a dive into what it takes to develop the same type of mobile app on the Windows Phone 7 platform.

FIGURE 7!45: iOS prompts for use of current location

c07.indd 227c07.indd 227 28/07/12 6:03 PM28/07/12 6:03 PM

Order your essay today and save 10% with the discount code ESSAYHELP