⭐ If you would like to buy me a coffee, well thank you very much that is mega kind! : https://www.buymeacoffee.com/honeyvig
Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies
Showing posts with label IPhone. Show all posts
Showing posts with label IPhone. Show all posts

Monday, November 25, 2013

Four Ways To Build A Mobile Application

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:
fastip-app-screens-500
The screenshots above show the application running as native iOS, PhoneGap and 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.
xcode-screen-500

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.
xcode-new-project-500
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:
new-project-options-500
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 as view 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:
storyboard-overview-500
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.
storyboard-properties-500
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.
storyboard-constraints-500
The constraints can also be manipulated programmatically. The Auto Layout mechanism is quite sophisticated and a bit daunting to use at first. Apple has an extensive 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 from UIViewController:
    file-new-options-500
  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:
    class-picker
  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:
    assistant-editor-icon
  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 the Control key, drag from the button to the interface area of your code.
    create-outlet-500
  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:
    create-action-500
    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 that these 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 the tipPercentage 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 the popViewControllerAnimated 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 UIAlertView dialog and will remain on the settings screen.
In the section above on view controllers and storyboards, I mentioned that the controls 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.view. The 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.
device-chooser-500
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:
breakpoint-variables-500-opt
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.

Saturday, October 27, 2012

10 Beautiful HTML5 Video & Audio Players for WordPress

A flood of HTML5 video plugins has become available in the past few months for WordPress 3.0, as HTML5 video is rapidly becoming the new standard for showing videos online. When the iPad came out in April 2010 with no support for Flash, sites that wanted to cater to the iPad and other mobile devices started serving HTML5 video. WordPress users have plenty of options for HTML5 video and audio plugins and many plugins also provide Flash or Silverlight fallback players, in case a visitor has a non-HTML5 browser.

MediaElement.js – HTML5 Video & Audio Player

MediaElement.js is an HTML5 video and audio player with Flash fallback. It supports IE, Firefox, Opera, Safari, Chrome and iPhone, iPad, Android. It’s got many audio and video shortcodes for easy use within posts and pages.
Check out http://mediaelementjs.com/ for a live example of the player.

Download Plugin

Projekktor Video Tag Extension

This plugin is based on the free (GPL) Projekktor Player framework and also includes flash-fallback. Notable extra features are the ability to generate a playlist, custom logo overlay, custom themed Youtube videos, and custom themed controls.

Download Plugin

VideoJS – HTML5 Video Player for WordPress

VideoJS, built on the VideoJS HTML5 video player library, is the most widely used HTML5 Video Player available. It allows you to embed video in your post or page using HTML5 with Flash fallback support for non-HTML5 browsers.
Check out a demo of the player at http://videojs.com/.

Download Plugin

External “Video for Everybody”

This plugin delivers ogg/theora (and optional webm) html5 video from an external storage location with fallbacks to flash, and links for download. It is designed to operate on media files hosted outside your WordPress site. Please note that it does not integrate with the Media library, and it does not create the media files.

Download Plugin

HTML5 and Flash Video Player

This plugin allows the addition of video (and other media) to a WordPress site. A full options menu is available with post-level overrides for endless customization. This plugin is low footprint, creating no tables, and uninstalls cleanly. It provides full support for Html5 Video, skinning the player, integration with Google Analytics and the capability to display ads from LongTail Solutions.

Download Plugin

Degradable HTML5 Audio and Video

The plugin enables HTML5 native playback for users with compatible browsers while offering an elegant degradation to other users through very lightweight Flash players. For HTML5 playback, it auto-detects and offers different alternatives, or degrades to Flash, and (failing even that) to download links.

Download Plugin

Universal Video

The plugin enables HTML5 native playback for users with compatible browsers while offering a simple degradation to other users through the use of the Flowplayer flash player. There’s no options panel – videos are added through the shortcode.

Download Plugin

HTML5 Multimedia Framework for WordPress

HTML5 Multimedia Framework is designed to be a highly customisable plugin for wordpress that allows advanced users to add their own JavaScript Libraries, or other JavaScript Libraries such as VideoJS and JW Player for HTML5. The framework is designed to be compatible with mobile devices that use WebKit or Opera Mobile/Mini and XML feeds such as RSS, and uses FlowPlayer for it’s flash fallback. Check out the demo.

Download Plugin

WP YouTube Lyte

WP-YouTube-Lyte inserts “Lite YouTube Embeds” in your blog. These look and feel like normal embedded YouTube, but don’t use Flash unless clicked on, thereby reducing download size & rendering time substantially. It also has experimental support for embedding html5 YouTube video is available (implementing YouTube’s new embed code), meaning WP-YouTube-Lyte allows for an entirely flash-less YouTube experience on your blog, displaying YouTube’s HTML5 video in h264 or the new WebM-codec.

Download Plugin

FlasHTML5 Video

This plugin is a WordPress implementation of the FlasHTML5 Video Javascript Library featuring HTML5 / Flash Video with Mobile Fallback. It supports all modern browsers (HTML5), all other browsers (Flash), and Android, iPhone, iPad, and iPod with HTML5.
Check out the demo at the plugin’s homepage.

Download Plugin

Wednesday, January 18, 2012

Getting started with PhoneGap

Getting started with PhoneGap

In this excerpt from the PhoneGap Beginner's Guide,this article goes over the biggest roadblock developers find with the mobile development framework: getting started and building simple apps for iOS, Android and BlackBerry

PhoneGap is, at heart, a set of project templates for different mobile operating systems, allowing us to ignore the details of each SDK and develop applications in a consistent fashion. The biggest roadblock developers find with PhoneGap is getting started – installing the SDKs and development environment to run those project templates. We're going to cover that task below.
In this article, we will:
  • Install Xcode and the iOS SDK for iOS development
  • Install the Android SDK and set up the emulator
  • Set up the BlackBerry Web Works development environment 
  • Build PhoneGap applications to all three platforms
So let's get to the first roadblock...

Operating systems

It's worth emphasising again: PhoneGap plays by the rules. If a vendor releases their SDK for just a single operating system, then you will have to use that OS to build and deploy your applications.
In detail, for each PhoneGap platform:
  • You can develop Android and HP webOS apps on any of the major desktop operating systems – Windows, Mac OS X, or Linux. Hooray!
  • You can develop Symbian Web Runtime apps on any OS, but you can only run the simulator from Windows.
  • Developing for BlackBerry is similar – the SDK can be installed on Windows or Mac OS X, but, at the time of writing, the simulator only runs on Windows.
  • The Windows Phone 7 SDK only runs on Ubuntu Linux, versions 10.04 and above. That one's a joke.
  • And, as you're no doubt aware, the iOS SDK requires the latest version, 10.6, of Mac OS X (and, according to the OS X EULA, a Mac computer as well).
Practically speaking, your best bet for mobile development is to get a Mac and install Windows on a separate partition that you can boot into, or virtualize using Parallels or VMWare Fusion. According to Apple's legal terms, you cannot run Mac OS X on non-Apple hardware; if you stick with a Windows PC, you will be able to build for every platform except iOS.
If getting a new computer sounds a bit too expensive, you'll probably want to skip the How To Buy a Dozen Phones chapter as well.

Dependencies

Nearly there! There are just a few other important tools you'll need to get up and running:
  • git: git is the best thing in the world (other opinions are available). More precisely, git is a distributed version control system, a superb tool for managing every aspect of software development. PhoneGap is developed with git at hand, and git is the best way to work with PhoneGap. You can find installation and usage information at git-scm.com/.

    For Mac and Linux users, I recommend using Git directly from the Terminal application. If you're on Windows, you may consider MsysGit.
  • ant: More precisely Apache Ant, is a Java-based build tool, similar to make. Unlike make, ant tasks are specified with XML. It is a very popular tool in the Java community. We'll use ant extensively for building Android and BlackBerry apps. You can get ant on your system from ant.apache.org, Detailed and current installation instructions are available there.

    Also, ensure that ANT_HOME is set correctly in your environment variables – this will ensure the PhoneGap ant scripts can run correctly.
  • Ruby: The droidgap build tooling depends on Ruby, a widely available programming language. If you're running on Mac OS X or Linux, Ruby should be available with your installation. An installer for the latest Ruby release for your system is available at www.ruby-lang.org/en/downloads/.

Getting started with iOS

So let's finally get something started – building applications on iOS. Firstly, we're going to get the developer tools installed on our Mac, and then we'll get PhoneGap itself up and running.

Time for action – getting an app running on the simulator

Let's start at Apple's iOS Dev Center. I'm going to assume that somebody intelligent enough would have purchased my book, and is fully capable of registering and creating an account. What next?
1. Download the latest SDK (4.3 at the time of writing) and the XCode and iOS package.
2. Wait for the three gigabyte download to finish. This may be a good time to get a cup of coffee.
3. Run the installer!
4. Launch Xcode, and start a New Project – select iOS and View-based Application. Name your application FirstApp when prompted.
5. The following screenshot shows what the final application should look like in Xcode:
6. Hit Build and Run on the Menu Bar – you should see the iPhone simulator launch on your screen. If you go to the home screen on your simulator, you should see the icon for your application:
7. This verifies that your setup is ready to begin writing PhoneGap applications for iOS. Congratulations, you're an iOS developer!

What just happened?

We just wrote our first iOS application!
Okay, so we didn't actually write any code – perhaps the project title counts as code, but it's a bit of a stretch. But if you can get this far – installing Xcode and launching the iPhone simulator – then the rest of the setup should be fairly easy.
One part that can also be tricky is deploying your new application to a physical iOS device. Please check Appendix, Deploying to an iOS Device, for help with this; you can also consult Apple's documentation at developer.apple.com, for the most up to date details.

Installing PhoneGap – iPhone

First things first – yes, it should be called PhoneGap iOS. As the old programming saying goes, there are only two hard problems in Computer Science: cache invalidation, off by one error and naming things.
You'll notice that neither of those problems involved PhoneGap, which is a doddle by comparison. Let's get going.

Time for action – Hello World with PhoneGap-iPhone

1. Open your OS X Terminal, and navigate to a folder you don't mind writing to. Make sure you have the Git installed and available in your PATH.
2. Enter the following command:
  1. $ git clone git://github.com/phonegap/phonegap-iphone.git
3. Now change into that directory, build the installer, and run it:
  1. $ cd phonegap-iphone
  2. $ make $ open PhoneGapLibInstaller.pkg
4. You'll see the PhoneGap GUI installer in front of you. Follow the instructions onscreen – the installation process takes up less than a megabyte on disk and doesn't require administrative privileges, so you shouldn't encounter any errors.
6. Quit and reopen Xcode if you still have it open – it will need to be restarted for the PhoneGap Project Template to be visible.
7. From the newly opened Xcode, select New Project again, and this time choose PhoneGap from the User Templates section, and PhoneGap-based Application from the main pane. Call your new project FirstGapApp (or, you know, something clever). You should see the familiar project view on Xcode, along with a www directory on the left-hand side.
8. Open www/index.html from the left pane of your application window. Scroll down to the JavaScript function onDeviceReady and add the following line of code:
  1. alert(‘Hello PhoneGap!’);
9. Hit Build and Run to see the results.
10. Your JavaScript code has now executed, and your PhoneGap application is ready to go.

What just happened?

We got our first PhoneGap application up and running, that's what – an application running natively on a mobile platform that is wholly controlled through HTML, JavaScript, and CSS. We should give ourselves a pat on the back for that alone!
We can get an initial sense of how PhoneGap works if we look at the left-hand side of the Xcode window, and contrast it with what we saw on FirstApp. Here are the important things to note:
  • There is a blue folder called www, next to a bunch of yellow folders similar to those in FirstApp. In Xcode's world, a blue folder is a directory on the file system that is bundled in with your project, whereas yellow folders are virtual directories containing project source code.

    It's important to be aware of this for one reason especially – as bundled files, PhoneGap source files are not automatically refreshed on each compile of your application. If you want to refresh your application in the simulator, or on your device, you will need to Clean it first.
  • There is a second blue Xcode project called PhoneGapLib.xcodeproj, below the main FirstGapApp Xcode project. This is the static PhoneGap library that was installed by the installer, and that GapFirstApp links to. If you wish, you can double- click on the project and edit away at the PhoneGap library – that's the beauty of open source software. But don't do that just yet.
  • The more eagle eyed among you will have noticed that the www folder contains only index.html, but it requires a file called phonegap.js on line 15. This JavaScript file isn't strictly necessary for PhoneGap development, but it does give you access to all of the PhoneGap APIs. By default, it's autogenerated when you build your application.
There are a couple of other differences between a PhoneGap-based Xcode application and a regular view-based iOS application, but we'll come to those in due time. Let's play around with our iPhone application for a bit, and then move onto the next platform.

Getting started with Android

Google's Android operating system is, in many ways, the antithesis of iOS: open instead of closed, and fragmented instead of integrated. This applies to the development environment as well – Android is a less bureaucratic environment than iOS, but has a few more rough edges along the way.

A note on development environments

It was the Roman playwright Terence, of the second century BC, who wrote Homo sum, humani nihil a me alienum puto; I am human, nothing human is alien to me. I feel likewise, except where the Eclipse IDE is concerned.
There are Eclipse plugin for both Android and BlackBerry development, which are certainly compatible with using PhoneGap on each platform. However, the major benefit of these plugins is their assistance with Java development, which is not the chief concern for developers using PhoneGap. Any text editor is sufficient for developing HTML, JavaScript, and CSS.
Rest assured, if Eclipse is your preferred environment, all of the content for these two platforms also applies in Eclipse.

Time for action – getting the SDK running

Android isn't tied to a single IDE in the manner iOS is tied to Xcode, although you can use the ADT plugin for Eclipse for a somewhat similar experience. There is also an Android plugin for IntelliJ IDEA available. For PhoneGap's purposes, this is a boon: we can go straight to a PhoneGap application, once the basic SDK is set up. Let's do that now, and then get on to the good stuff:
1. Download the latest SDK package (r11 at the time of writing) from developer.android.com/sdk/index.html.
2. Unpack the contents of the SDK to a safe location, and then add that location to your operating system's PATH environment variable.
3. Launch the SDK and AVD manager – on Windows, run the SDK Setup.exe program, otherwise enter android at your prompt.
4. Install some packages! Select Available Packages on the left, and click everything that looks good. In particular, you'll want the SDK Platform, Google APIs, and Documentation for the version of the Android API you want to target and the latest API tools. I would recommend installing 2.2, with APIs 8: the emulator for 2.3 has a bug with PhoneGap, and later releases are targeting tablets, primarily. Be forewarned: this will take a while to download.
5. Now we need to create an AVD. Unlike iOS, there isn't a default simulator provided with the SDK, so we need to create one (there are lots of reasons for this, but no good ones). Select Virtual Devices on the left, then press New... on the right.
6. The settings are up to you, but a few recommendations:

Go for the latest release of the Google APIs. Google APIs offer access to proprietary services offered by Google, in addition to the open source Android APIs. Most consumer devices will have these APIs available. The one major vendor that does not use Google's APIs is China Mobile – if you're developing for the Chinese market, just use the stock Android APIs. WVGA800 (480 pixels by 800) is a good resolution to go with.
7. The SD card should have at least a few hundred megabytes – this should be available to you on the menu shown below:
8. Select your new AVD from the list and hit Start (if the screen looks funny, adjust the screen size when prompted – I find around 8-10 inches gets a good size). It will take a while to boot up, during which time you can read the OS's source code, and bask in Google's openness/beneficence/omniscience.
It may not be pretty, but you can read the source.

What just happened?

It's a bit more subtle than iOS, but we did more or less the same thing as the first tutorial of the chapter – got the SDK up and running, and launched an emulator.
One thing that's immediately apparent is that targeting the Android platform is not the same thing as targeting the iPhone device, or even the iPhone, iPod Touch, and iPad family of devices. There isn't a uniform screen resolution, operating system revision, or amount of storage space we can rely on, and the SDK tools don't allow us to easily build an emulator to represent, say, the HTC Desire phone. We need to use our own judgment to figure out the best emulator for our given application.
More than anything, we want to run applications directly on devices, to get the best sense of how they work. Luckily, this is easier on Android than on either of the other major platforms we will cover in depth. To allow app deployment via USB:
  • Open the top-level Settings on your Android device
  • Select Applications
  • Check Unknown sources, to install non-Market applications
  • Select Development
  • Check USB debugging
If you're going to do serious Android development, we highly recommend getting a developer phone directly from Google – see google.com/phone for available devices. I recommend HTC's Nexus one, if it is available in your region. You can also purchase an Android Dev Phone from the Android Market – market.android.com – though you will need a developer account, which costs $25 US. The Android emulator experience is frustrating enough, and the deployment to phone process is smooth enough, to make this the outstanding approach.
Of course, we don't have any applications yet, but that should change shortly.

PhoneGap Android

Android is the second most mature PhoneGap platform, after PhoneGap-iPhone, and the development process is highly polished at this point. To avoid confusion, we should emphasise the difference between the two related, but distinct, parts of PhoneGap Android:
  • The PhoneGap Library, or phonegap.jar: The Java library that links the PhoneGap APIs into the Android WebView, and initiates an app with that WebView
  • Droidgap: A Ruby-based generator/utility for creating and deploying PhoneGap Android projects
Droidgap was created, at least partially, from frustration with the Android development process. It attempts to streamline and enhance a lot of the long-winded steps of Android development. However, it's a little brittle at the time of writing, so your patience is appreciated.

Time for action – Hello World on PhoneGap Android

1. Firstly, ensure that you have all the dependencies set up: ant, git, and Ruby should all be available on your path. Please see earlier in this chapter for help getting these set up.
2. Let's start like phonegap-iphone, with a git clone into somewhere sensible:
  1. $ git clone git://github.com/phonegap/phonegap-android.git
3. The next bit is a bit tricky, so bear with me. Ensure the Ruby executable bin/droidgap is somewhere you can access, either in your PATH or somewhere you can access directly (as in the screenshot below).
4. Switch to the example directory, run droidgap create, then switch to the example_android directory (again, I'm relying on the screenshot to make sense of this):
5. Build and install the application (this requires either a running simulator or an attached device):
  1. $ ant debug install
6. Pull up your AVD/non-virtual device, and check out your first PhoneGap Android project!

What just happened?

Well, the not-quite-as-elegant-as-we-had-hoped command line tooling for PhoneGap Android has generated a sample application that demos all of the PhoneGap functionality.
The droidgap create command is, currently, the smoothest way to create a sample PhoneGap Android application from a given set of client-side assets. We can then use the predefined ant tasks to build the application itself and install directly to our virtual or physical device.
The PhoneGap Android tools allow you, as a developer, to be further removed from the nitty gritty of the Java implementation and focus on the client-side technology that counts.

What's in a PhoneGap Android application, anyway?

One side effect of the droidgap app creation process is that it's possible to miss the structure of the application itself, which you can't really do with iOS development through Xcode. Here's what the project contents look like:
Some parts of note:
  • AndroidManifest.xml is the equivalent of Application-Info.plist on PhoneGap iPhone—global settings, like the package name of your app, are put here, and in res/values/strings.xml.
  • Your PhoneGap code is in assets/www, not just www.
  • There are three copies of icon.png in the res folder, based on the DPI of the target screen (this is in common with iOS, just with a different directory structure). Droidgap just copies the same file in each location, but you can change this when getting ready to submit your application to the Android Market.
  • Since it's Java at heart, the qualified name of your app (in this case, com.phonegap.example) has to be the name of your main Android activity. It falls under "tedium we try to avoid" but you should be aware that your AndroidManifest has to match your directory structure, or bad things start to happen.

Have a go hero – going further with Android

Check out the other Android command line tools – in particular, adb logcat and adb shell. Obviously Android has a lot more of the OS open than iOS, but what are some of the cool things you can do with that?
If you're familiar with the Ruby programming language, look into the source for droidgap (in the lib directory of the phonegap-android git repository). See if you can figure out what exactly it's doing, and how it works.

Getting started with BlackBerry web works

On to BlackBerry, the oldest of the three mobile platforms we're focusing on and the one with the most baggage.
In the annals of PhoneGap lore (two months ago), PhoneGap supported BlackBerry through the BlackBerry JDE Component Pack, on devices running RIM's BlackBerry OS 4.2 and above. While the code is still available, it has since been deprecated. It was, frankly, a nightmare, both in terms of PhoneGap's implementation and the browser that was ultimately exposed. You can look at some of the older tutorials on the PhoneGap wiki for evidence of these horrors.
As of BlackBerry OS 5.0, there is a better way – the BlackBerry Web Works SDK. Based on the W3C's web widget specification, which dovetails very nicely with PhoneGap, BlackBerry Web Works move PhoneGap BlackBerry from the slowest major PhoneGap platform to one of the very fastest.
As with every platform, and with web development in general, you still need to tread with caution regarding JavaScript and CSS support. In particular, if you do choose to work with devices running less than 5.0, the embedded browser is quite poor.
On top of that, the OS 6.0 devices (right now, just the BlackBerry Torch), have a credible, WebKit-based browser to hook into. Whatever next!

Time for action – your first PhoneGap BlackBerry app

First things first: to run the BlackBerry simulator (as of the time of writing), you will need to be running on Windows – if you've been following from the start of the chapter, now is a good time to throw your Mac out the window. Or reboot into your other partition, whatever works.
1. Let's start by downloading the SDK: na.blackberry.com/eng/ developers/browserdev/widgetsdk.jsp.
2. You're probably used to this bit by now, but here it goes: run the SDK installer. One thing to note is that you should install to C:/, rather than C:/Program Files/; this will avoid some issues with permission when running the ant scripts.
3. Clone the PhoneGap repo (in this case, we're using the git bash program to run git on Windows – other options are available):
  1. $ git clone git://github.com/phonegap/phonegap-blackberry- webworks.git
4. Like with PhoneGap Android, we'll use ant to generate our sample application:
  1. $ ant create –Dproject.path="C:\Development\FirstApp"
5. One quick gotcha is here: if you're running a 32-bit build of Windows, you will need to edit the project.properties file in your FirstApp directory, changing the bbwp.dir variable to point to where you have installed the SDK. The ant scripts can be a little bit brittle with older versions of Windows, so make sure that the WebWorks Packager is referenced correctly.
6. From your FirstApp directory, launch the simulator:
  1. $ ant load-simulator
Or, if you're ambitious/determined enough to have your code signing set up already, launch your application on a device:
  1. $ ant load-device
7. A couple of processes will be launched – the BlackBerry simulator and the Mobile Data System Connection Server (MDSCS). The simulator is self explanatory, but the MDSCS is necessary for the simulator to server network requests.
I'm not sure exactly how much detail you'll want on this, but here goes: on a BlackBerry device, all network traffic is proxied through RIM's servers. On a BlackBerry simulator, everything is proxied through a local server. If you close that server, your application will silently fail, and an army of RIM ninjas will attack you while you sleep. Allegedly.
8. At any rate, the simulator is launched now. To find the PhoneGap Sample, hit the BlackBerry button (the one with seven circles resembling a B), then Downloads:
You should now see the icon for the sample application:
9. The next challenge is to launch the application. I'm sure you can figure this one out:

What just happened?

We got another application running on another mobile platform, using PhoneGap to fill in the gaps. Huzzah!
Things should be getting more familiar now – we use the PhoneGap tools to generate a sample project that contains a JavaScript reference to all of the PhoneGap APIs, and from then on we only need to worry about writing and rewriting the HTML, JavaScript, and CSS.
If we look at the structure of a BlackBerry Web Works PhoneGap application, things should look familiar:
Once more, we have a www directory containing our index.html and phonegap.js files, a build.xml file (just like Android) for running ant tasks, an external library (www/ext/ phonegap.jar) linking the native PhoneGap APIs, and an XML-based configuration file (www/config.xml) that defines global settings for our application.
Though there are major differences between the browser environments on each of these platforms, which we will cover in pain-staking detail over the rest of the book, a high-level look at PhoneGap on each of these platforms shows the commonalities.

Code signing for BlackBerry

Something I glossed over a bit earlier is Code Signing – like Apple with iOS, RIM requires you to sign your applications, with their approval, before you can install them on your (their) devices. Phew. It's an involved process, and we're all tired at this point, but here's an overview:
  1. Go here: www.blackberry.com/SignedKeys/.
  2. Fill out the form.
  3. Allow RIM to relieve you of $20.
  4. After a week or so, follow the instructions they email to you.
Say what you like about Apple, at least they're efficient at taking your money.

Have a go hero – cross-platform fun

Already in this chapter, we've seen how PhoneGap gives similar structures to applications you can deploy to multiple mobile platforms. Try to take that a step further – can you link all three platforms to a single development directory? Do you need separate copies of phonegap.js for each platform?
Try to edit each platform's sample application. How do you remove, rebuild, and reinstall applications on each platform? Be sure to familiarise yourself with the documentation for each platform, in case any of these tasks become difficult – we'll try to take the SDKs for granted as we move on through the book.

Summary

Well that was a lot of fun (ahem). The mobile development landscape is strewn with clunky SDKs – if nothing else, the attrition that this chapter has covered should highlight the scope of the problem that PhoneGap aims to solve. From here on, things go a lot smoother.
Specifically, we covered:
  • Getting an iOS PhoneGap application up and running
  • Doing likewise for Android
  • And once more for BlackBerry Webworks
We also discussed how you can begin to automate your workflow, using ant tasks where available. We're starting to look towards building cross-platform applications, rather than starting with a single platform and porting over – and now that we've installed all of these SDKs, we're going to spend as little time with them as possible.
Over the coming chapters, we will begin to add more and more functionality to our mobile applications, while building on the base we have established here. Our next step is to see how to structure mobile applications to get the best use out of PhoneGap.

Wednesday, December 7, 2011

iPhone Emulators for windows


The AIR iPhone is a desktop application created with Adobe AIR and Adobe Flex 3, it simulates the UI of the iPhone. It has the capabilities to make calls, receive calls, check voicemail, add contacts and even send voice messages, all using Ribbit. To use the calling functionality you will need an account with Ribbit.
Download – AIR iPhone v3.60
You will also need the Adobe Integrated Runtime if you don't have it.

MobiOne is a powerful and free iPhone and Palm Pre emulator (currently for Windows only) with a drag-n-drop mobile-web visual designer for mockups and mobile HTML code generation functionality.
It has various mobile design templates, updated OSS components, screen capture, multi-touch, gesture support and more.
MobiOne iPhone Emulator
The tool doesn't require any SDK to be installed as it takes advantage of HTML5, CSS3 and JavaScript for development.
MobiOne also supports PhoneGap (an open source, JS-based mobile development toolkit)