AppThwack – Automated testing of iOS and Android apps on real devices in the cloud

AppThwack maintains a remote device lab of hundreds of iOS and Android devices and an automation infrastructure that allows you to run automated test scripts in parallel on real devices, not emulators. AppThwack supports all popular automation frameworks. With AppThwack, you can

  • Execute your tests, in parallel, across 100s of iOS and Android phones and tablets with results available in minutes
  • Initiate tests through a simple web interface or Jenkins Plug-in
  • View results in web-based dashboard or download for offline viewing
  • Analyze reports in real-time that include high-level results, low-level logs, pixel-perfect screenshots, and performance trends (CPU, Memory, Threads, Frame draw time)
  • Integrate report data with CI and other business flow applications

AppThwack offers a free 7-day trial period. Start testing with AppThwack today!

How to Test Your App on an iOS Device

Provisioning an application for testing on either a physical device or for App Store distribution can be a nightmare for beginners. However, every iOS developer has to tackle this hurdle at some point. In this article, I hope to give you a good understanding of how to properly provision an application for testing on a physical device.

1. iOS Developer Program

As I mentioned in a previous tutorial in this session, if you plan to run development code on a physical device or you intend to publish an application on the App Store, you’ll first need to enroll for the iOS Developer Program.

To do so, open a new browser window and go to the iOS Dev Center. Sign in with your Apple developer account and click the Learn More link in the iOS Developer Program section on the right.

On the next page, click the Enroll Now button and follow the steps to complete the enrollment.

Keep in mind that it can take several days for your application to be accepted. Apple manually approves each application, which means that you won’t have access to the iOS Developer Program until you get the green light from Apple.

2. Create a Certificate Signing Request

After enrolling for the iOS Developer Program, you’ll notice that the iOS Dev Center has a slightly different interface.

In the iOS Developer Program section on the right, you no longer see the Learn More link you clicked to enroll for the program. Instead, you see links to Certificates, Identifiers & ProfilesiTunes Connect, Apple Developer Forums, and the Developer Support Center. In this article, we’ll be working in the Certificates, Identifiers & Profiles section. Click the link to the Certificates, Identifiers & Profiles section on the right.

The provisioning process starts with the creation of an iOS Development Certificate. A certificate is an electronic document that links your digital identity with other information, such as your name, email, and company information.

A development certificate consists of a secret private key and a shared public key. If you are familiar with SSL certificates for securing a website, then you probably already know what a certificate is and how it works.

Xcode uses the private key of the certificate to cryptographically sign your application binary. To obtain a development certificate, we first need to create a certificate signing request or CSR.

You can create a CSR using OS X’s Keychain Access utility, which you can find in the Utilities folder of the Applications folder. Open the Keychain Access menu, select Certificate Assistant and choose the option labeled Request a Certificate From a Certificate Authority….

Fill out the form by entering your name and the email address with which you signed up for your Apple developer account. Leave the certificate authority email address (CA Email Address) blank and make sure to select the option labeled Saved to disk to save the certificate signing request to your system. Leave the checkbox labeled Let me specify key pair information unchecked.

Click Continue, specify a location to save the CSR, and click Save. Browse to the location you specified to make sure the CSR was generated. In Keychain Access, under the Keys category, you can see that the private and public keys have been added to your login keychain.

3. Create a Development Certificate

Head back to the Certificates, Identifiers & Profiles section in the iOS Dev Center. Select the Certificates section in the column labeled iOS Apps.

Click the plus button in the top right and follow the guide for creating a development certificate. In the first section, Development, select iOS App Development, and click Continue.

The next view tells you how to create a CSR. Feel free to click Continue since you’ve already have a CSR ready to upload.

It’s time to upload the CSR we generated earlier. Click the Choose File button at the bottom, select the CSR, and click Generate. It may take a few seconds while the development certificate is being generated.

The certificate should be valid for one year. Click the Download button to download the certificate to your development machine.

Locate the certificate on your development certificate and double-click it to add it to your login keychain.

4. Adding a Device

You cannot run an iOS application on a random device. You need to specify on which devices your iOS application should run by adding one or more iOS devices to the iOS Dev Center.

Browse to the Certificates, Identifiers & Profiles section of the iOS Dev Center, click the Devices tab in the iOS Apps section, and click the plus button in the top right. To register a device, enter a name for the device and he device’s UDID. The UDID is an identifier that uniquely identifies an iOS device. Note that the UDID is not the same as the device’s serial number.

You can find the UDID of a device by connecting the device with your machine and launching Xcode’s Organizer. You can open the Organizer by selecting Organizer from the Window menu. Select the Devices tab at the top and select the device you’re interested in. The 40 character alphanumeric string next to the label Identifier is the device’s UDID.

The first time you connect an iOS device to your Mac and you view the device in Xcode’s Organizer, you should see a button labeled Use for Development.

When you click this button, Xcode will connect to the iOS Dev Center on your behalf. During this process, Xcode will ask you for the credentials of your iOS developer account if you haven’t added those to Xcode’s Preferences > Accounts. Xcode will then prepare your device for development by downloading the provisioning profiles that contain the device, more about this later.

The long and the short of it is that it used to be a pain to prepare devices for development. Xcode has made this much easier by asking the iOS Dev Center for the necessary data behind the scenes. When a device can be used for development, a green indicator is shown on the right of the device’s name in Xcode’s Organizer.

5. Create an App ID

An app ID is an identifier that uniquely identifies an application on iOS. It’s much like the device’s UDID that uniquely identifies a device. The app ID is used by the operating system for security reasons and it’s an essential component of Apple’s Push Notification and iCloud services, among others.

The app ID of an application consists of your application’s bundle identifier prefixed with a unique 10 character bundle seed ID generated by Apple. What’s a bundle identifier? Do you remember when you set up your first application? Even though I didn’t cover the bundle identifier in detail, you implicitly specified a bundle identifier for your project by giving your application a name and specifying a company identifier. By default, the bundle identifier is your application’s name prefixed with your project’s company identifier. You can change the bundle identifier to whatever you like. It’s recommended to adopt the reverse-domain naming convention, for example, com.tutsplus.my-first-application. The complete app ID would then be xxxxxxxxxx.com.tutsplus.my-first-application.

To create a new app ID in the iOS Dev Center, navigate to the Certificates, Identifiers & Profiles section, click iOS Apps, and choose App IDs from the menu on the left. To create a new app ID, click the plus button in the top right.

Start by giving your app ID a descriptive name so you can find it later. Leave the app ID prefix field untouched. In the section App ID Suffix, enter your application’s bundle identifier. Make sure you enter it in the section labeled Explicit App ID.

You can replace the application name in the bundle identifier by an asterisk, for example, com.tutsplus.*. This is useful if you intend to create a suite of applications that need to be able to share keychain access or don’t require keychain access at all. The asterisk or wild-card character needs to be the last component of the bundle identifier. This type of app ID is a wildcard app ID—as opposed to an explicit app ID.

6. Create a Provisioning Profile

With the development certificate and the app ID in place, it’s time to create a provisioning profile for your application. Before we start, it might be useful to explain what a provisioning profile is, because this is something that confuses a lot of new iOS developers.

To quote Apple’s documentation, “a provisioning profile is a collection of assets that uniquely ties developers and devices to an authorized iOS Development Team and enables a device to be used for testing.” In other words, a provisioning profile contains the information that the operating system needs to verify whether an application is permitted to run on a specific device. This implies that the provisioning profile needs to be installed on each device the application needs to run on.

It will become clearer if we create a provisioning profile for your application so let’s do that now. In the Certificates, Identifiers & Profiles section of the iOS Dev Center, select the Provisioning Profiles tab in the iOS Apps section. Click the plus button in the top right to create a new provisioning profile. Select iOS App Development in the section labeled Development and click Continue.

In the next step, select the app ID you created a few minutes ago and click the Continue button.

Select the development certificate from the list of certificates to associate the new provisioning profile with the correct certificate and click Continue.

You then need to select the devices you wish to link to the provisioning profile. Remember that only these devices will be able to run your application during development.

Give the provisioning profile a descriptive name so you can easily find it later. Click Generate and download the provisioning profile to your development machine. Double-click the provisioning profile to add it to Xcode.

If you wish to add more devices to an already existing provisioning profile, than you can do so by editing the provisioning profile. All you need to do is download the new profile and install it on all the devices you wish to test with. In other words, you don’t need to create a new provisioning profile if all you want to do is add or remove devices.

7. Configuring the Project

Before you can build and run your application on your device, you need to update the build settings of the target in your Xcode project.

Open the Xcode project that you created during the previous tutorial and select the project from the Project Navigator on the left. Select the first item in the list of targets and click the tab labeled Build Settings at the top.

Don’t be overwhelmed by the numerous build settings. Scroll through the list and search for the section titled Code Signing. In this section, search for the subsection titled Code Signing Identity and set the Debug configuration to match iOS Developer. It’s usually located under the Automatic heading.

8. Build and Run

If you followed the steps correctly, you should now be able to build and run your application on your device. Before running your application, make sure that you properly set the active scheme by selecting your device from the drop down menu.

Conclusion

Creating and managing certificates, provisioning profiles, app IDs, and test devices can be a daunting task—and it often is for most developers. I hope that this article has given you a sturdy foundation.

Don’t hesitate to read this article a few times to really understand how the different pieces fit together. It will make debugging issues related to provisioning much easier and I can guarantee you that you’ll run into such issues at some point in your iOS development career.

Installing the Best Android Dev Environment: Intellij IDEA and Genymotion Emulator

Every few months, I check out new build tools. When I first began building Android apps, I used Google’s Android Toolkit, Eclipse and Google’s Emulators. Pretty quickly, I grew impatient with Google excruciatingly slow emulator and switch to always deploy to my device.

Then I started using VirtualBox based emulators, switched from Eclipse to Intellij IDEA, and finally switched to using Genymotion’s emulator. So here are the steps necessary to set up your Mac and the links to where to find everything.

I will be posting a video of these instructions to YouTube in about a week. I have a lot of editing to do to take about three hours of video to about 10 minutes.

Installing the complete Android development kit is going to take about two hours, possibly more. I highly recommend that you do it all in one sitting, to avoid accidentally re-installing an installed component or even worse not installing a component. We are going to need five components:

  1. Oracle’s Java Development Kit (JDK)
  2. Android Developer’s Toolkit (ADT)
  3. JetBrains’ Intellij IDEA Community Edition
  4. Oracle’s VirtualBox
  5. Genymotion Android Emulator

JDK

There is a bit of disagreement about which version of the JDK to use for Android development. The current version of Java, at the time of writing, is JDK 7. JDK 8 is currently in beta. But the Android developer’s official page list JDK 6 as the version to use. Until the developer’s page changes, I am going to recommend that we use JDK 6. Here is the link to that version on Apple’s developer website. You will need to be registered as a developer in order to access this page.

https://developer.apple.com/downloads/index.action#

In Categories, clear everything except Developer Tools and use “java” as the search term. Don’t use JDK 7 or 8. I have never been able to get them to work correctly. If you do so, you will have to clean up your dev box on your own. Select the version labeled, “Java for OS X 2013-005 Developer Package”. Be sure that this is your version. There are others with really close names, but close is not good enough. Click the disclosure arrow to expand it. Click the Java Developer Package… link on the right hand side to download the .dmg file. Once it has finished downloading, double click the .dmg file to open it, then double click the JavaDeveloper.pkg file to start the install.

To validate the installation we need to use the Terminal. Open a Terminal window and type:

javac -version

It should respond with: javac 1.6.0_65. If it does you are good to go. If it doesn’t STOP, don’t go any further we need to fix it before we do anything else.

Troubleshooting

There are two issue that I am aware of that can cause issues. There are probably more but I haven’t encounter them yet, so I can’t help you with them.Issue number one: You have another version of Java installedIf the response is: javac 1.7.0_45 or some other version number, you have another version of the JDK installed. First thing we need to do is verify that you have version 6 installed. From the terminal type:cd /Library/Java/JavaVirtualMachines returnls returnThe ls command is the roughly the same as the dir command on a Windows machine. We should see 1.6.0_65-b14-462.jdk listed. If so, we just need to add a JAVA_HOME to our profile. If we don’t see 1.6.0_65-b14-462.jdk listed, we didn’t install it correctly. I suggest trying the install again.Issue number two: We need to add JAVA_HOMEJAVA_HOME informs all tools looking for the JDK where it lives. To add we once again need to go to Terminal. From the command line enter:vim ~/.bash_profilevim is a text editor from the dawn of time. It has a funky UI, which is a bit hard to grok, but luckily all we need to do is add one line and save it. Enter the following line:export JAVA_HOME=”/Library/Java/JavaVirtualMachines/1.6.0_65-b14-462.jdk/Contents/Home/”Then press escape XX, which is the escape key followed by shift X shift X. This will save our change and exit vim. Our profile should now point JAVA_HOME to our newly installed JDK 6. At this point I usually restart my machine to make sure all of my change get picked up, but I have been told all you need to do is log out then back in again.

ADT

Since we don’t want to use Eclipse, all we need to download is the Android Developer Tools, not the ADT Bundle. Just the ADT. 

In your browser go to: http://developer.android.com/sdk/index.html
Scroll down to the bottom of the page.Click the expando, “USE AN EXISTING IDE”Click the button, Download the SDK Tools for MacThe folder, “android-sdk-macosx, will download load to your machine, I recommend copying it to your application folder since most of the contents in it are executables. Once you have copied the folder to your applications folder you will need to run the app “android” in order to install SDK and other tools that you need. You will need to override OS X’s security setting in order to run the android app. Find it using the finder, then hold down the control key while double clicking the app name. A security warning will pop up. Don’t freak out. This is to be expected. Confirm that you want to run the android app. In a couple of seconds, the Android SDK installer program will appear.For now only install Android SDK 19, or whatever the latest version is. Each version is kind of big and we don’t want to spend all day installing SDKs we don’t need. Besides it is pretty easy to add more SDKs later.

Intellij IDEA

We are finally ready to install the actual IDE. Use your browser to go to:http://www.jetbrains.com/idea/download/

Click the button to download the Community Edition. It will take a few minutes to download the .dmg file.Launch Intellij in order to finish the installation. Once the Welcome menu shows:Double click Create New ProjectSelect Application Module from the Android section on the left sideWe need to configure both the JDK 6 and our Android SDKClick the New… button in the upper right hand cornerFirst we will configure the JDKIn the file finder dialog box navigate to:/Library/Java/JavaVirtualMachines/1.6.0_65-b14-462.jdk/Contents/HomeClick ChooseClick the New… button again. Now lets find our android SDK folder.In the file finder dialog box navigate to:  /Applications/android-sdk-macosxClick Choose

VirtualBox

VirtualBox is a free virtual machine app. It is required by the Genymotion emulator.Go to: https://www.virtualbox.org/wiki/Downloads
Click the link: VirtualBox 4.3.8 for OS X hosts -> x86/amd64Double click the dmg file and follow instructions.

Genymotion

Genymotion is a virtual machine based emulator for Android. It not a Google product. It is unbelievably fast. It is fast enough to play arcade games on it. They have a wide variety of devices in the emulator library. My normal workflow is to build and test on emulators and once I am confident I will test on actual hardware. Their emulators are also nice when demo an app on a projector.


It is free for private use. You must be registered in order to download emulators.Go to: http://www.genymotion.com/To register. They will send a link to your email address in order to confirm it. Click the link and you are in.Download the emulator from the download pageDouble click the dmg fileDrag the Genymotion app to the application folderDrag the Genymotion.shell app to the application folderDouble click the Genymotion app in your application folder to launch itClick the Add button to download an emulated deviceI would recommend initially downloading a Nexus 4 (phone). You should now be able to build and deploy an Android app to the Genymotion device.

Debugging iOS PhoneGap Apps with Safari’s Web Inspector

At some point, something will go wrong in your PhoneGap application, and you’ll want to know why. Ideally, you’ll be able to reproduce the problem in a desktop web browser, fix it, and move on. Inevitably, however, you’ll run into a problem that is only reproducible on a device. If this happens to you on iOS, and you are targetting iOS 6 or higher, you’re in luck… well, aside from that nasty defect you just found, but hey, it happens!

With Safari 6 and higher (OS X only, sorry Windows) you can use Safari’s developer tools to remotely debug web pages in mobile Safari on an iOS device.

But wait, there’s more!

Not only can you remotely debug web pages in mobile Safari, you can remotely debug any web page in any plain old UIWebView, which just happens to include that UIWebView hosting your PhoneGap application. Note that you can only inspect UIWebView content in apps that were transferred to a device from XCode. Sorry, no inspecting apps downloaded from the App Store!

Here’s how to set up for debugging PhoneGap apps with Safari’s web inspector.

Disable Private Browsing

Open your device’s Safari settings and ensure that Private Browsing is turned off. Remote debugging will not work if Private Browsing is enabled. I learned this the hard way after wasting a couple hours trying to set up remote debugging.

Disable private browsing

Enable Web Inspector

Tap the Advanced tab on your device’s Safari settings and ensure that Web Inspector is turned on.

Enable web inspector

Enable Safari’s Develop Menu

On your desktop or laptop, open Safari’s Preferences and click on the Advanced tab. Check the box to Show Develop menu in menu bar.

Enable Safaris develop menu

Start Web Inspector

Launch your app either in the iOS simulator or on a physical device. If you are using a physical device you’ll need to connect it to your desktop or laptop with the standard USB cable. Once the app has launched, switch to Safari, select the Develop menu item, then find the entry corresponding to the web page you want to debug.

Attach remote web inspector

Now you can use web inspector just like you would to debug a web page.

Use remote web inspector

Pitfalls

One disadvantage to using web inspector like this is that you cannot attach early enough to debug issues that occur at start up. You can fake it a little by adding a delay to your start up code withsetTimeout, but even that won’t help catch every issue. You’ll have to rely on the old standbysalert() and console.log() to figure out these issues, and of course, just opening your app’s main HTML page in a browser can be quite helpful for diagnosing start up problems.

Audio Tutorial for iOS: File and Data Formats

Before working with the iPhone, I had sadly little experience with sound formats. I knew the difference between .WAVs and .MP3s, but for the life of me I couldn’t tell you exactly what a .AAC or a .CAF was, or what the best way to convert audio files was on the Mac.

I’ve learned that if you want to develop on the iPhone, it really pays to have a basic understanding of file and data formats, conversion, recording, and which APIs to use when.

This audio tutorial is the first in a three-part Audio Tutorial series covering audio topics of interest to the iPhone developer. In this article, we’ll start by covering file and data formats.

File Formats and Data Formats, Oh My!

The thing to understand is that there are actually two pieces to every audio file: its file format (or audio container), and its data format (or audio encoding).

File Formats (or audio containers) describe the format of the file itself. The actual audio data inside can be encoded many different ways. For example, a CAF file is a file format, that can contain audio that is encoded in MP3, linear PCM, and many other data formats.

So let’s dig into each of these more thoroughly.

Data Formats (or Audio Encoding)

We’re actually going to start with the audio encoding rather than the file format, because the encoding is actually the most important part.

Here are the data formats supported by the iPhone and a description of each:

  • AAC: AAC stands for “Advanced Audio Coding”, and it was designed to be the successor of MP3. As you would guess, it compresses the original sound, resulting disk savings but lower quality. However, the loss of quality is not always noticeable depending on what you set the bit rate to (more on this later). In practice, AAC usually does better compression than MP3, especially at bit rates below 128kbit/s (again more on this later).
  • HE-AAC: HE-AAC is a superset of AAC, where the HE stands for “high efficiency.” HE-AAC is optimized for low bit rate audio such as streaming audio.
  • AMR: AMR stands for “Adaptive Multi-Rate” and is another encoding optimized for speech, featuring very low bit rates.
  • ALAC: Also known as “Apple Lossless”, this is an encoding that compresses the audio data without losing any quality. In practice, the compression is about 40-60% of the original data. The algorithm was designed so that data could be decompressed at high speeds, which is good for devices such as the iPod or iPhone.
  • iLBC: This is yet another encoding optimized for speech, good for voice over IP and streaming audio.
  • IMA4: This is a compression format that gives you 4:1 compression on 16-bit audio files. This is an important encoding for the iPhone, the reasons of which we will discuss later.
  • linear PCM: This stands for linear pulse code modulation, and describes the technique used to convert analog sound data into a digital format. In simple terms, this just means uncompressed data. Since the data is uncompressed, it is the fastest to play and is the preferred encoding for audio on the iPhone when space is not an issue.
  • μ-law and a-law: As I understand it, these are alternate encodings to convert analog data into digital format, but are more optimized for speech than linear PCM.
  • MP3: And of course the format we all know and love, MP3. MP3 is still a very popular format after all of these years, and is supported by the iPhone.

So which do I use?

That looks like a big list, but there are actually just a few that are the preferred encodings to use. To know which to use, you have to first keep this in mind:

  • You can play linear PCM, IMA4, and a few other formats that are uncompressed or simply compressed quite quickly and simultaneously with no issues.
  • For more advanced compression methods such as AAC, MP3, and ALAC, the iPhone does have hardware support to decompress the data quickly – but the problem is it can only handle one file at a time. Therefore, if you play more than one of these encodings at a time, they will be decompressed in software, which is slow.

So to pick your data format, here are a couple rules that generally apply:

  • If space is not an issue, just encode everything with linear PCM. Not only is this the fastest way for your audio to play, but you can play multiple sounds simultaneously without running into any CPU resource issues.
  • If space is an issue, most likely you’ll want to use AAC encoding for your background music and IMA4 encoding for your sound effects.

The Many Variants of Linear PCM

One final and important note about linear PCM encoding, which again is the preferred uncompressed data format for the iPhone. There are several variants of linear PCM depending on how the data is stored. The data can be stored in big or little endian formats, as floats or integers, and in varying bit-widths.

The most important thing to know here is the preferred variant of linear PCM on the iPhone is little-endian integer 16-bit, or LEI16 for short. Note that this differs from the preferred variant on the Mac OSX, which is native-endian floating point 32-bit. Because audio files are often created on the Mac, it’s a good idea to examine the files and convert them to the preferred format for the iPhone.

File Formats (or Audio Containers)

The iPhone supports many file formats including MPEG-1 (.mp3), MPEG-2 ADTS (.aac), AIFF, CAF, and WAVE. But the most important thing to know here is that usually you’ll just want to use CAF, because it can contain any encoding supported on the iPhone, and it is the preferred file format on the iPhone.

Bit Rates

There’s an important piece of terminology related to audio encoding that we need to mention next: bit rates.

The bit rate is the number of bytes per second that an audio file takes up. Some encodings such as AAC or MP3 let you specify the number of bytes to compress the audio file to. When you lower the bytes per second, you lose quality as well.

You should choose a bit rate based on your particular sound file – try it out at different bit rates and see where the best match between file size and quality is. If your file is mostly speech, you can probably get away with a lower bit rate.

Here’s a table that gives an overview of the most common bit rates:

  • 32kbit/s: AM Radio quality
  • 48kbit/s: Common rate for long speech podcasts
  • 64kbit/s: Common rate for normal-length speech podcasts
  • 96kbit/s: FM Radio quality
  • 128kbit/s: Most common bit rate for MP3 music
  • 160kbit/s: Musicians or sensitive listeners prefer this from 128kbit/s
  • 192kbit/s: Digital radio broadcasting quality
  • 320kbit/s: Virtually indistinguishable from CDs
  • 500kbit/s-1,411kbit/s: Lossless audio encoding such as linear PCM

Sample Rates

There’s one final piece of terminology to cover before we move on: sample rates.

When converting an analog signal to digital format, the sample rate is how often the sound wave is sampled to make a digital signal.

Almost always, 44,100Hz is used because that is the same rate for CD audio.

How to remotely install apps on your smartphone

You can download and install apps to your iPhone and Android phone without being anywhere near it. That sorcery is this? It isn’t sorcery. It’s the internet. And it takes almost no effort to set up.

On Android

If you have an Android phone, you can quickly and easily remotely install apps to your phone without having to tinker with any settings. Visit the Google Play store from your computer and log in using the Google account that’s associated with your phone. Next, find the app that you want to install and go to its information page, then press the Install button for that app.

Select the device you want to install the app on, then press Install.

Once you click Install, you’ll be presented with a box that tells you which permissions the app needs (whether it needs to access your contacts or connect to the Internet, for instance), as well as a drop-down list of the devices associated with your Google account. Select the phone or tablet you want to install the app on from this list, then press Install. After a few moments, your phone will begin installing the app.

Pretty easy, right? You betcha.

On iOS

Toggle this switch…

iOS 7 comes with a similar feature, but you need to make sure it’s switched on first. To check, open the Settings app, scroll down, then tap iTunes & App Store. From here, look for the Automatic Downloads section, then toggle the Apps slider to the on position (the toggle switch will turn green). If you want to have updates downloaded to your phone automatically, switch the Updates toggle to the on position as well.

…then download your app. It will appear on your iPhone’s homescreen a few moments after you purchase it on your computer.

Next, open iTunes on your Mac or PC, then go to the iTunes Store, and sign in using the Apple ID associated with your phone. Go to the App Store, then find an app you want to download. Press the Download buttom—it will be labelled with the app’s price—and after a few moments it will be downloaded to both your computer and your phone.

On Windows Phone 8

Setting up your Windows phone for remote app installation is similar to the process for iOS. Start by going to the Settings app on your phone and then select Find My Phone from the list. Next, look for the checkbox labelled Send apps to my phone using push notifications (not SMS) and tap it if it isn’t checked already.

Now go to the Windows Phone store, then mouse over Explore My Phone in the upper-right corner and sign in with the Microsoft account associated with your phone. Find the app you want to install, and press the Buy or Install button (which button label you see will depend on whether the the app is paid or free).

Once you do that, the Windows Phone store will pick your default device and install that app to it after a few moments.

Four Ways To Build A Mobile Application, Part 1: Native iOS

The mobile application development landscape is filled with many ways to build a mobile app. Among the most popular are:

  • native iOS,
  • native Android,
  • PhoneGap,
  • Appcelerator Titanium.

This article marks the start of a series of four articles covering the technologies above. The series will provide an overview of how to build a simple mobile application using each of these four approaches. Because few developers have had the opportunity to develop for mobile using a variety of tools, this series is intended to broaden your scope.

Hopefully, armed with this knowledge, you will be in a better position to choose the right development tools for your mobile application’s needs. In this first article in the series, we’ll start with some background and then dig into iOS.

I’ve built the same simple application with each technology to demonstrate the basic concepts of development and the differences between the platforms and development tools. The purpose of this series is not to convert you to a particular technology, but rather to provide some insight into how applications are created with these various tools, highlighting some of the common terms and concepts in each environment.

FasTip is a simple application to calculate tips. Because this is a simple example, it uses the standard UI controls of each platform:

The screenshots above show the application running as native iOSPhoneGapand native Android applications. Appcelerator Titanium uses native controls, so it looks the same as the native iOS and Android applications. Our application has two screens: a main screen where the tips are calculated, and a settings screen that enables the user to set a tip percentage. To keep things simple and straightforward, we’ll use the default styles of each environment.

The source code for each app is available on GitHub.

Native iOS Development

Most applications in Apple’s App Store are written in the Objective-C programming language, and developers typically use Xcode to develop their applications.

OBTAINING THE TOOLS

To build an iOS app, you must use Mac OS X; other operating systems are not supported. The development tools that you’ll need, iOS 7 SDK and Xcode 5, are free of charge, and you can run the app that you build in the iOS simulator, which is part of the iOS SDK. To run your app on a real device and make it available in Apple’s App Store, you must pay $99 per year.

CREATING A NEW PROJECT

Once you have installed Xcode, you’ll want to create a new project. Choose “Create a new Xcode project” from the welcome screen or via File → New Project in the menu.

For a simple application such as this one, “Single View” is appropriate. Upon clicking “Next,” you will be presented with a dialog to enter some basic information about your application:

The value that you enter in the “Class Prefix” option tells Xcode to attach that unique prefix to every class that you generate with Xcode. Because Objective-C does not support “namespacing,” as found in Java, attaching a unique prefix to your classes will avoid naming conflicts. The “Devices” setting lets you restrict your application to run only on an iPhone or an iPad; the “universal” option will enable the application to run on both.

NAVIGATION CONTROLLERS AND VIEW CONTROLLERS

The screen functionality of iOS applications is grouped into what are known asview controllers. Our application will have two view controllers: one for the main screen and one for the settings screen. A view controller contains the logic needed to interact with the controls on a screen. It also interacts with another component called the navigation controller, which in turn provides the mechanism for moving between view controllers. A navigation controller provides the navigation bar, which appears at the top of each screen. The view controllers are pushed onto a stack of views that are managed by the navigation controller as the user moves from screen to screen.

STORYBOARDS: BUILDING THE USER EXPERIENCE VISUALLY

Starting with iOS 5, Xcode has had storyboards, which enable developers to quickly lay out a series of view controllers and define the content for each. Here’s our sample application in a storyboard:

The container on the left represents the navigation controller, which enables the user to move from screen to screen. The two objects on the right represent the two screens, or view controllers, that make up our app. The arrow leading from the main screen to the settings screen is referred to as a segue, and it indicates the transition from screen to screen. A new segue is created by selecting the button in the originating view and then, while the Control key is pressed, dragging the mouse to the destination view controller. Apple’s documentation provides more detail about this process.

In the example above, we can see that a text field has been selected, and the property panel is used to adjust the various attributes of the controls. When this application was created, the “universal” app option was selected, enabling the app to run on both an iPhone and iPad. As a result, two versions of the storyboard file have been created. When the app is running on an iPhone or iPod Touch, the _iPhone version of the file will be used, and the _iPad version will be used for iPads. This allows a different layout to be used for the iPad’s larger display. The view controller will automatically load the appropriate layout. Keep in mind that if your storyboards expose different sets of controls for the iPad and the iPhone, then you must account for this in the code for your view controller.

In addition to directly positioning items at particular coordinates on the screen,you can also use the Auto Layout system that was introduced in iOS 6. This enables you to define constraints in the relationships between controls in the view. The storyboard editor enables you to create and edit these constraints.

The constraints can also be manipulated programmatically. The Auto Layout mechanism is quite sophisticated and a bit daunting to use at first. Apple has anextensive guide on Auto Layout in its documentation.

Associating Storyboards With Your Code

To access the storyboard objects from the code, you must define the relationships between them. Connecting items from the storyboard to your code via Xcode is not obvious if you’re used to other development environments. Before you can do this, you must first create a view controller to hold these associations. This can be done with the following steps:

  1. Choose File → New File.
  2. In the dialog that appears, choose “Objective-C class”:
  3. In the next dialog, give your class a name and ensure that it inherits fromUIViewController:
  4. Upon clicking “Next,” you’ll be asked to confirm where in the project the file should be saved. For a simple project, picking the main directory of the app is fine.
  5. Upon clicking “Next,” you’ll see that a new set of files has been created for your view controller. Now, associate that newly created view controller with the view controller in your storyboard.
  6. With the storyboard open, click on the view controller. In the “Identity Inspector” panel, pick the “Class” that this view controller is to be associated with:
  7. Once this process is completed, the code for your view controller will be properly referenced by the storyboard entry.

To reference the controls that you’ve dragged onto a storyboard from your Objective-C code, you’ll need to define these relationships. The storyboard editor has an “assistant editor” view to help with this. Basically, it’s a split-pane view that shows both the storyboard and your code. In this example, we’ll reference a button that’s already been placed on the storyboard:

  1. First, ensure that you’ve completed the steps above to associate the view controller class with the corresponding view controller in the storyboard.
  2. Choose the assistant editor by clicking the icon that looks like this:
  3. A split-pane view will open, with the storyboard on the left and your view controller class on the right.
  4. Select the button in your storyboard and, while holding down theControl key, drag from the button to the interface area of your code.
  5. The resulting dialog will enable you to create an “outlet” for the button in your code. Simply give the button a name, and click the “Connect” button in the dialog. You may now reference the button in the view controller from your code.
  6. Let’s hook up a method to be invoked when a person taps on the button. Select the button again, and use the same Control-and-drag maneuver to drop a reference into the interface section of your view controller.
  7. This time, in the dialog box that appears, we’ll associate an “action,” rather than an outlet. Choose “Action” from the “Connection” drop-down menu, and enter a name like this:
    For the “Event,” use the default of “Touch Up Inside,” and press the “Connect” button.
  8. Note that your class now has an interface with two entries in it:
@interface FTSettingsViewController ()
@property (weak, nonatomic) IBOutlet UIButton *myButton;
- (IBAction)tappedMyButton:(id)sender;
@end

The IBOutlet item is used to identify anything that you’re referencing from the storyboard, and the IBAction is used to identify actions that come from the storyboard. Notice also that Xcode has an empty method where you can place the code to be run when the user taps on the control:

- (IBAction)tappedMyButton:(id)sender {
}

The process above does take some getting used to and could certainly be made more intuitive. After some practice, it will get less awkward. You might find it useful to bookmark the section of the Xcode documentation that describes how to “Connect User Interface Objects to Your Code.”

As we’ll see later, you can also add objects to the view and manipulate their properties programmatically. In fact, applications of even moderate complexity typically perform a lot of manipulation in code. For complex apps, some developers eschew the storyboard and use the code-based alternative almost entirely.

GETTING INTO THE CODE

For even the most basic of applications to function, some code must be written. So far in the storyboard, we’ve laid out our user interface and the interactions between the view controllers. But no code has been written to perform the calculations, to persist the settings of the tip percentage and so on. That is all done by you, the developer, in Objective-C.

When an application is running, its overall lifecycle is handled by something called an “application delegate.” Various methods in this delegate are called when key events in the application’s lifecycle occur. These events could be any of the following:

  • the application is started,
  • the application is moved to the background,
  • the application is brought to the foreground,
  • the application is about to be terminated,
  • a push notification arrives.

The events above are handled in a file called AppDelegate. For our sample application, the default handling of these events is just fine; we don’t need to take any special action. The documentation has an overview of the application’s lifecycle and of responding to changes in an app’s state.

The next area of attention is the view controller. Just as with the application delegate, the view controller has its own lifecycle. The view controller’s lifecycle includes methods that are invoked when the following happens:

  • the view controller has been loaded;
  • the view controller is about to appear or has appeared on the screen;
  • the view controller is about to disappear or has disappeared from the screen;
  • the bounds of the view have changed (for example, because the device has been rotated) and the view will be laid out again.

The main code for our application is in the FTViewController.m file. Here is the first bit of code that initializes our screen:

- (void)viewWillAppear:(BOOL)animated
{
    // Restore any default tip percentage if available
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    float tipPercentage = [defaults floatForKey:@"tipPercentage"];
    if (tipPercentage > 0) {
        _tipPercentage = tipPercentage;
    } else {
        _tipPercentage = 15.0;
    }
    self.tipAmountLabel.text = [NSString stringWithFormat:@"%0.2f%%", _tipPercentage];
}

In this application, we want to use whatever tip percentage value was stored in the past. To do this, we can use NSUserDefaults, which is a persistent data store to hold settings and preferences for an application. Keep in mind thatthese values are not encrypted in any way, so this is not the best place to store sensitive data, such as passwords. A KeyChain API is provided in the iOS SDK to store such data. In the code above, we’re attempting to retrieve thetipPercentage setting. If that’s not found, we’ll just default to 15%.

When the user taps the “Calculate Tip” button, the following code is run:

- (IBAction)didTapCalculate:(id)sender {
    float checkAmount, tipAmount, totalAmount;

    if (self.checkAmountTextField.text.length > 0) {

        checkAmount = [self.checkAmountTextField.text floatValue];
        tipAmount = checkAmount * (_tipPercentage / 100);
        totalAmount = checkAmount + tipAmount;

        self.tipAmountLabel.text = [NSString stringWithFormat:@"$%0.2f", tipAmount];
        self.totalAmountLabel.text = [NSString stringWithFormat:@"$%0.2f", totalAmount];

    }

    [self.checkAmountTextField resignFirstResponder];

}

We’re simply reading the value that the user has inputted in the “Amount” field and then calculating the tip’s value. Note how the stringWithFormat method is used to display the tipAmount value as a currency value.

When the user taps the “Settings” button in the navigation controller, the segue that we established in the storyboard will push the settings’ view controller onto the stack. A separate view controller file, FTSettingsViewController, will now handle the interactions on this screen. Pressing the “Done” button on this screen will run the following code:

- (IBAction)didTapDone:(id)sender {

    float tipPercentage;
    tipPercentage = [self.tipPercentageTextField.text floatValue];

    if (tipPercentage > 0) {

        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setFloat:tipPercentage forKey:@"tipPercentage"];
        [defaults synchronize];

        [[self navigationController] popViewControllerAnimated:YES];

    } else {

        [[[UIAlertView alloc] initWithTitle:@"Invalid input"
                                    message:@"Percentage must be a decimal value"
                                   delegate:nil
                          cancelButtonTitle:@"ok"
                          otherButtonTitles:nil] show];

    }

}

Here we’re retrieving the value from the text field and making sure that the inputted value is greater than 0. If it is, then we use NSUserDefaults to persist the setting. Calling the synchronize method is what will actually save the values to storage. After we’ve saved the value, we use thepopViewControllerAnimated method on the navigation controller to remove the settings view and return to the prior screen. Note that if the user does not fill in the percentage correctly, then they will be shown the standard iOS UIAlertViewdialog and will remain on the settings screen.

In the section above on view controllers and storyboards, I mentioned that thecontrols in a view can be manipulated programmatically. While that was not necessary for our application, the following is a snippet of code that creates a button and adds it to a particular location on the screen:

CGRect buttonRect = CGRectMake(100, 75, 150, 80);
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame = buttonRect;
[myButton setTitle:@"Click me!" forState:UIControlStateNormal];
[self.view addSubview:myButton];

Generally speaking, all of the controls that you place in a view extend from an ancestor class named UIView. As such, buttons, labels, text-input fields and so on are all UIViews. One instance of a UIView is in the view controller. This can be referenced in your view controller’s code as self.viewThe iOS SDK positions items in a view based on a frame, also referred to as CGRect, which is a structure that contains the x and y coordinates of the item, as well as the width and height of the object. Note in the code above that the button is instantiated and assigned a frame (location and size) and then added to the view controller’s view.

RUNNING AND DEBUGGING AN IOS APPLICATION

When Xcode and the iOS SDK are installed, so is the iOS simulator, which simulates an iOS device directly on your machine. Xcode has a drop-down menu that allows you to select different device configurations. Pressing the “Run” button in the upper-left corner will build the app and then run it in the chosen simulator.

Using the menu above, you can switch between iPhones and iPads of different sizes, as well as between Retina and non-Retina versions of each device.

Debugging is done simply by clicking in the left margin of the code editor, where the line numbers appear. When the execution of your app reaches the breakpoint, the app will stop and the variable values in effect at that moment in time will appear below the code editor:

Some things, such as push notifications, cannot readily be tested in the simulator. For these things, you will need to test on a device, which requires you to register as an Apple developer for $99 a year. Once you have joined, you can plug in your device with a USB cable. Xcode will prompt you for your credentials and will offer to “provision” the device for you. Once the device is recognized, it will be shown in the same menu that allows you to switch between device simulators.

In Xcode, by going to Window → Organizer in the menu, you can display a tool that enables you to manage all of the devices visible in Xcode and to examine crash logs and more. The Organizer window also lets you take and export screenshots of your application.

Summary

Thus far, we’ve seen the basics of developing a simple native iOS application. Most applications are more complex than this, but these are the basic building blocks:

  • Xcode
    The development environment
  • Storyboards
    For laying out and configuring the user interface
  • View controllers
    Provide the basic logic for interacting with each of the views defined in the storyboards
  • Navigation controllers
    Enable the user to navigate between the different views

LEARNING RESOURCES

To get started with iOS development, you might want to consult these useful resources:

This concludes the first segment of our tour of app development. I hope it has given you some insight into the basic concepts behind native app development on iOS. The next article in this series will cover how to build the same application using native Android development tools.

(http://mobile.smashingmagazine.com)