Article Series
Introduction
In this article we will learn to write mobile apps using native, hybrid, and responsive development techniques for popular device platforms like iOS and Windows Phone for now, and later Android and BlackBerry.
While the this article covers only the front end development for mobile app, but I would strongly recommend to evalute DreamFactory for backend REST API creation in minutes! DreamFactory is dramatically changing the landscape of how we develop and manage back-end REST APIs. This breakthrough technology could reduce time and cost of mobile app to unexpected levels.
Figure - iOS, Android, BlackBerry, and Windows Phone
iOS Native App
Figure - iOS 7 on iPhone5S
iOS is a mobile operating system installed on iPhone, iPod Touch, iPad, and iPad Mini. Objective-C is used to write mobile apps for these devices using Cocoa Touch API and XCode. Cocoa is used for gesture recognition, animation etc., while XCode is an integrated development environment for iOS development.
To test the app on a physical device or to publish it on App Store, an yearly $99 fee is required. To better read app code, let's take a look at Objective-C, which is very similar to C++.
Figure - iOS7 Home Screen
Objective-C
You write iOS apps using Objective-C, a superset of C that uses SmallTalk OOP syntax. It was developed almost 33 years ago (in 1980). Let's get a hold of Objective-C first.
Figure - Objective-C class header
To create a class in Objective-C, we add two files: header and method file:
@interface Button {
}
@end
@implementation Button
@end
Now we will add class assets, i.e., members and methods. To add a private member:
@interface Button {
@private
BOOL visible;
}
@end
@implementation Button
BOOL visible;
@end
Note the parenthses right after Button
, which is a way to declare a Class Extension.
@interface Button() {
BOOL visible;
}
@end
@implementation Button
@end
To add a protected member (by default, class members are protected):
@interface Button {
bool rounded;
}
@end
@interface Button {
@protected
bool rounded;
}
@end
To add a public member:
@interface Button {
@public
NSString* text;
}
@end
To add a public property:
@interface Button {
}
@property NSString* text;
@end
@interface Button {
}
@property (readwrite) NSString* text;
@end
@interface Button {
}
@property (readonly) NSString* text;
@end
@interface Button {
}
@property (readonly, getter=caption) NSString* text;
@end
@interface Button {
NSString* buttonText;
}
@property NSString* text;
@end
@implementation Button
@synthesize text = buttonText;
@end
@interface Button {
}
@property NSString* text;
@end
@implementation Button
@synthesize text;
@end
@interface Button {
}
@property (readwrite, nonatomic) NSString* text;
@end
@interface Button {
}
@property (readwrite, copy) NSString* text;
@end
You can find more about properties and fundamental Objective-C constructs here.
To add a static member:
@interface Button {
}
NSString *defaultText;
@end
To inherit from a class:
@interface Button {
}
@end
@interface RoundedButton : Button {
}
@end
Methods in Objective-C starts with + (for static or class methods) and - (for public or instance methods), followed by a return type in parentheses, method name with colon, and a list of colon separated parameters:
+ (int) add : (int) a : (int) b;
- (int) square : (int) a;
Figure - Objective-C method syntax
We cannot apply @public
, @private
, and @protected
access specifiers to methods. Also methods can not be private, protected but we can roughly simulate this using Class Extension. To add public, private, and static methods in a class:
@interface Button {
}
@end
+ (void) setDefaultText : (NSString*) val;
- (int) textLength;
@interface Button() {
- (bool) hasDefaultText;
}
@implementation Button
+ (void) setDefaultText : (NSString*) val {
}
- (int) textLength {
}
- (bool) hasDefaultText {
}
@end
To add a constructor, add a method init
which returns an id
object. The id
object is like void*in
:
@implement Button
- (id) init
{
self = [super init];
if (self != nil)
{
}
return self;
}
@end
@implement Button
- (id) init
{
}
- (id) init : (NSString*) text
{
}
- (id) init : (NSString*) text : (bool) rounded
{
}
@end
Objective-C does not support method overloading. However, as the method name (or selector) in Objective-C includes parameter colons as well, it may look like method overloading but does not behave like real C++ overloading. The above constructors are not overloaded but rather three different selectors i.e., (init
, init:
, init::
).
Figure - Method name includes colon in Objective-C
Note that the following will give an error:
@implement Button
- (id) init : (NSString*) text
{
}
- (id) init : (bool) rounded
{
}
@end
To create an instance of a class:
@implement Button
- (id) init
{
}
- (id) init : (NSString*) text
{
}
- (id) init : (NSString*) text : (bool) rounded
{
}
+ (void) Tester
{
Button* b1 = [[Button alloc] init];
Button* b2 = [Button new];
Button* b3 = [[Button alloc] init: text:@"Hello world"];
Button* b4 = [[Button alloc] init: text:@"Hello world" rounded:true];
[b1 release];
[b2 release];
[b3 release];
[b4 release];
}
@end
Calling release
on an object invokes dealloc
. To add, dealloc
(or destructor) to free up resource:
@implement Button
- (id) init
{
_someResource = [foo retain];
return self;
}
- (id) dealloc
{
[_someResource release];
[super dealloc];
}
@end
To implement or adopt an interface (i.e., protocol) on a class:
@protocol ITouchable
- (void) tap : (int) x: (int) y;
@optional
- (void) doubleTap : (int) x: (int) y;
@required
- (void) multiTap : (int) x1: (int) y1 : (int) x2: (int) y2;
}
@interface Button : NSObject<ITouchable> {
}
@end
@implement Button
- (void) tap : (int) x: (int) y
{
}
- (void) multiTap : (int) x1: (int) y1 : (int) x2: (int) y2
{
}
@end
You can add methods to an existing class using a Category:
@interface NSString(MyNsString) {
}
- (NSString*) stripHtml;
@end
@implement NSString(MyNsString)
- (NSString*) stripHtml
{
}
@end
A nice Objective-C cheat sheet by RayWenderlich is available in PDF form here.
Figure - Objective-C Cheat Sheet
Objective-C Memory Management
There are three ways to manage memory in Objective-C:
- Manual Retain Release (MRR)
- Garbage Collection (GC)
- Automatic Reference Counting (ARC)
To understand existing code bases, you should get a grip on all three.
Manual Retain-Release (MRR) - 1980 - present
Figure - MRR is the oldest memory management technology
MRR is based on a one simple rule: "If you own an object, you have to release it". You can own an object if you call a method which:
- begins with alloc, copy, new, init, or retain e.g.
alloc
, newObject
, or - contains Copy or Create e.g.,
mutableCopy
.
An object that you own by the virtue of A) and B) (or ownership methods) is your 'responsibility' and you should give up ownership of object by calling release or autorelease. You must not release object for any other case.
When you own an object by calling ownership methods, the object's retainCount
is incremented by 1 and when you call release
or autorelease
it is decremented by 1. When retainCount
reaches to 0, object's dealloc
method is called and it is destroyed. This looks simple, but you should never use retainCount
because it is misleading.
- (NSString*) newStr: (NSString*) input {
NSString* s = [NSString stringWithString:@"Hello world"];
return s;
}
- (NSString*) newStr: (NSString*) input {
NSString* s = [NSString stringWithString:@"Hello world"];
[s retain];
return s;
}
- (NSString*) newStr: (NSString*) input {
NSString* s = [[NSString alloc] initWithString:@"Hello world"];
return s;
}
- (NSString*) newStr: (NSString*) input {
NSString* s = [[NSString alloc] initWithString:@"Hello world"];
[s autorelease];
return s;
}
- (NSString*) newStr: (NSString*) input {
NSString* s = [NSString stringWithString:@"Hello world"];
NSString* s2 = [s copy];
return s2;
}
There difference between release
and autorelease
methods is that, release
is called immediately; decrementing retainCount
by 1 and calling dealloc
if it becomes zero. On the other hand, autorelease
just 'puts' the object in a special pool, called autorelease pool, that the Application Kit creates. autorelease pool is basically a NSAutoreleasePool
object, which is created on on the main thread at the beginning of every cycle of the event loop, and drains at the end, thereby releasing any auto-released objects.
Figure - A call to
autorelease method puts an object in a special pool
int main(void) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *s = [[[NSString alloc] init] autorelease];
[pool drain];
}
If you are using GC, then drain sends message (objc_collect_if_needed
) for GC while in MRR and ARC drain is same as calling release on NSAutoreleasePool
.
You can nest pools and autorelease
object will be added to nearest pool.
int main(void) {
NSAutoreleasePool *pool1 = [[NSAutoreleasePool alloc] init];
NSString *s1 = [[[NSString alloc] init] autorelease];
NSAutoreleasePool *pool2 = [[NSAutoreleasePool alloc] init];
NSString *s2 = [[[NSString alloc] init] autorelease];
[pool2 drain];
[pool1 drain];
}
However recommended way is to use @autoreleasepool
.
@autoreleasepool {
NSString *s1 = [[[NSString alloc] init] autorelease];
@autoreleasepool {
NSString *s2 = [[[NSString alloc] init] autorelease];
}
}
Garbage Collection (GC) - 2006 - 2011
Figure - GC even collects cyclic object references
GC is a runtime technology and it is not available in iOS, so we will discuss it in brief. With GC, a low-priority thread collects unused objects. In GC mode, calls to own and object or release it result in no operation. For new iOS app, ARC is recommended but you can use plain-old MRR.
Automatic Reference Counting (ARC) - 2011 - present
Figure - ARC inserts retain-release calls at compile time
ARC, available in iOS5 onwards, is a compile time technology which inserts necessary retain-release calls at the time of code compilation and sets weak references to nil once object is deallocated. This is different from GC which runs as a separate background process and collects unused objects at runtime.
ARC, however can not collect cyclic references while GC can. When using ARC, you cannot call retain
, release
, retainCount
, autorelease
, or dealloc
. You can find complete list of ARC rules here.
In later parts of this series we will see how to develop iOS app using XCode and Cocoa framework.
Windows Phone Native App
Figure - Windows Phone 8 on Nokia Lumia 520
Windows Phone (WP) is a mobile OS by Microsoft. WP app is developed using Windows Phone SDK and Visual Studio IDE. An XML markup language, XAML, is used to develop user interface while you can use C#, VB.NET or one of your favorite language to hook up user interface events.
Following are OS versions available on various phones:
Windows Phone release | Operating system version |
Windows Phone 8 | Windows Phone OS 8.0 |
Windows Phone 7.5 | Windows Phone OS 7.1 |
Windows Phone 7 | Windows Phone OS 7.0 |
There is an annual fee to publish Windows Phone apps to the Windows Store.
Annual Fee
Figure - Annual Fee
Every mobile platform provider takes some kind of annual fee:
- To unlock certain number of mobile devices to test your app.
- To publish paid or free app to their market place.
Here is an interesting summary:
Platform | Cost per Year | Test devices Limit | Free apps Limit | Paid apps Limit | File Size Limit |
Window Phone | $19 (earlier $99)
DreamSpark Student = Free | 3 | 100 | Unlimited | XAP = 1GB[1] |
Apple iOS | Developer = $99
Enterprise = $299
University = Free
| 100[2] | Unlimited | Unlimited | IPA = 60MB[3]
EXT = 2GB |
Google Play | Developer = $25 (Life time) | Unlimited | Unlimited | Unlimited | APK = 50MB
EXT = 2x2GB
|
Black Berry | $0 | Unlimited | Unlimited | Unlimited | COD = 128KB[4]
EXT = 14MB |
[1] On most platforms anything over 20-50MB requires Wi-Fi or docked connection with laptop and can not be downloaded over-the-air data connection.
[2] Although you may remove a device from your account, Apple will continue to count it against your 100 device limit.
[3] Apple puts a 60MB limit (page 232) on executable file. Language packs, images and other resources could be bundled separately on SD card.
[4] 128KB = 64KB code + 64KB data. On all mobile platforms including Black Berry, you can download resources from a website when needed, and cache them locally on SD Card.
Figure - SD (top), mini SD, micro SD cards
Windows Phone Project
Figure - Windows Phone Project Types
There are many types of Windows Phone project you can start with. Let's start with Windows Phone App project to discuss some of the common Windows Phone development ideas.
A page
Usually you start Windows Phone app by adding necessary XAML files (or pages).
Figure - What you can usually add to Windows Phone Project
An (almost) empty page will look like this. Beside having namespaces at the top, there is a Grid
called 'LayoutRoot
' with two rows below. The first row has "Auto" height, which means it will 'adjust' its height based on its content. The second row height is set to "*" which means it will take up 'all' available space.
<phone:PhoneApplicationPage
x:Class="PanoramaApp1.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d"
shell:SystemTray.IsVisible="True">
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
</Grid>
</Grid>
</phone:PhoneApplicationPage>
Grid Panel
Within this page you add controls inside Grid ContentPanel
. Usually you will place Stack
, Grid
, or Canvas
panel first to layout controls. Inside a panel you place actual Phone Controls e.g., Buttons, TextBlock, Textbox, etc.
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<TextBox Text="Enter User Name" Grid.Row="0" />
<TextBox Text="Enter Password" Grid.Row="1" />
<Button Content="Sign In" Grid.Row="2"/>
</Grid>
Figure - Grid with two TextBoxes and a Button control
Windows Phone Toolkit
On a different note, Windows Phone Toolkit provides some really interesting controls and transitions.
Figure - Windows Phone Toolkit
Stack Panel
Like you layout controls in a table like format using Grid panel, you can use Stack panel to place controls one on the top of other.
<StackPanel>
<TextBox Text="Enter User Name" />
<TextBox Text="Enter Password" />
<Button Content="Sign In" />
</StackPanel>
Canvas Panel
Or for absolute positing use Canvas panel. Note that Canvas.Top
is used to specify absolute position.
<Canvas>
<TextBox Text="Enter User Name" />
<TextBox Text="Enter Password" Canvas.Top="72" />
<Button Content="Sign In" Canvas.Top="144" />
</Canvas>
Figure - Controls layout using Canvas panel
Controls are kind of shrunk to default 'Auto' width because we have not specified 'absolute' width (e.g., Width="456").
Landscape Left or Right?
A mobile phone can be in one of three orientations: Portrait, Landscape (Left or Right).
Events - Click or Tap?
You can add Button Tap event to handle Sign In. For every Tap on a mobile a Click is fired right as well with a delay of (+/-) 300 ms. So event handling in Click, will cause scrolling, cancelling, and other user interactions to feel really sluggish.
private void Button1_Tap(object sender, EventArgs e)
{
if (MyDbContext.SignIn(this.UserNameTextBox.Text, this.PasswordTextBox.Text))
{
}
else
{
}
}
Event Bubbling
Note that if Button Tap event is not available, the runtime will search parent controls until it finds an event handler.
Figure - Windows Phone event bubbling
Windows Phone 8 supports phones that have WVGA, WXGA, and 720p resolutions. This differs from Windows Phone OS 7.1, which supported only WVGA resolution.
Navigation
A mobile application usually consists of a large number of pages and various pages are shown to end user based on his interaction of app. In Windows Phone, you can navigate and pass parameter among pages using NavigationService
.
void passParam_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/SecondPage.xaml?msg=" + textBox1.Text, UriKind.Relative));
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string msg = "";
if (NavigationContext.QueryString.TryGetValue("msg", out msg))
textBlock1.Text = msg;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
NavigationService.GoBack();
}
Panorama Control
Windows Phone Panorama Control is a way to provide a long canvas with multiple panels to host grids, text boxes, labels and other controls. Panorama control encourages the user to explore the potentially unrelated contents before going to next level of details.
Figure - Panorama control to provide summary of unrelated contents in pages
Pivot Control
On the other hand a Pivot Control provides a way to filter related contents in pages. Checkout an email app using pivot control to filter all, unread, and flagged messages in pages.
Figure - Pivot control to filter related items in pages
Speech Recognition
Typing in small device is a real pain. In Windows Phone, it is very easy to enable voice recognition in your application using SpeechRecognizerUI
class.
private async void ButtonSR_Click(object sender, RoutedEventArgs e)
{
this.recoWithUI = new SpeechRecognizerUI();
SpeechRecognitionUIResult recoResult = await recoWithUI.RecognizeWithUIAsync();
MessageBox.Show(string.Format("You said {0}.", recoResult.RecognitionResult.Text));
}
Figure - Windows Phone Voice Recognition Experience
Windows Phone runs only one app at a time to preserve battery and to provide resources necessary for smooth running of app. If user switch application, app state is tomb-stoned and its process is terminated except if it is an background location tracking app. When user switch back, app should restore its state from storage.
Mobile App Development - Possible Paths
Figure - Which path is the right one?
There are three paths to develop mobile app hybrid, native and HTML 5.
Hybrid
For run-of-the-mill business applications, hybrid app provides necessary functionality and performance most of the time. A hybrid mobile app is build using HTML5, CSS3, JavaScript, PhoneGap and it runs on iOS, Android, Windows Phone and Black Berry.
Figure - A hybrid mobile app using Knockout and ASP.NET MVC
Native
For game development that requires higher performance, graphics and lower file size, native app is the right choice but you can do game development using PhoneGap too.
HTML 5
Finally, at minimum any new website (or web app) should be build using HTML 5 and responsive layout technologies like Bootstrap or Foundation. Responsive web design gives a minimum entry point to device world which is expanding in size every day.
Do you have native platform skills?
Another factor that influences choice of path is that native app development requires skills in languages of each platform (i.e. C#, Objective-C and Java) while hybrid apps could be developed using familar CSS3, HTML5 and JavaScript. So learning curve is low for hybrid app and therefore could be developed relatively quick at lower cost.
Platform independent or specific (with high performance)?
Beside learning curve, native apps are platform specific, so you have to develop one app for each platform while hybrid apps will run on many platform e.g., iOS, Android, Windows Phone and Black Berry. However, at times clients are looking for platform specific user interface with high performance. In such cases you may want to choose native app over hybrid. If performance is not important, then mobile libraries like KendoUI Mobile, Sencha Touch and jQuery Mobile theming features provide necessary look and feel for various platforms and various versions of same platform.
When mobile app user experience matters?
Platform specific user experience is important for general purpose mobile applications released for masses. Obviously for such applications, end users do not expect iOS user interface on Android device or Android kind of user experience on Windows Phone. But for business applications targeted for a single enterprise or division, clients may opt for uniform user experience on all platforms to lower down development and training cost. If platform specific user experience is important, a better route is to select hybrid mobile framework like KendoUI Mobile.
Figure 1 - A hybrid app on various platforms built using Kendo UI Mobile
Which platforms hybrid framework supports?
One more case where you may want to choose native over hybrid is 'platform supported'. Consider for example, Sencha Touch does not support Windows 7 Phone. To write Windows 7 specific mobile app, you may want to go for native app. See figure below for platform support by Sencha Touch:
Figure 1 - Limited Platform Support by Sencha Touch
PhoneGap feature support for hybrid apps
Just like platform support for hybrid framework is limited, to certain extent that is the case with PhoneGap as well. However PhoneGap 3.0 feature support is suffice for most of your needs if performance is not the key decision factor. For example, iPhone and BlackBerry Compass are inaccessible using PhoneGap while Media support is unavailable for BlackBerry, WebOS, Symbian, and Bada.
Figure - PhoneGap 3.0 feature support for various platforms
Before you submit PhoneGap app
While submitting PhoneGap application to a market place like Apple iTunes, Google Play or Windows Phone Marketplace, you have to be cautious to include all the capabilities that are provided by PhoneGap, no matter if your application is using anyone of these or not.
Add to your application, following PhoneGap capabilities: data services, movement and directional sensor, microphone, music and video library, owner identity, camera, contacts, camera & compass. Not mentioning them will either result in application rejection or not functioning correctly on end user device.
Hopefully with these pointers, it will be easy for you to decide whether you should go for hybrid, native or HTML 5 mobile app. As most people prefer hybrid app due to low entry barrier as well as release to multiple platforms, so we will first look into hybrid mobile app technologies.
Hybrid Mobile App
Hybrid app is 'hybrid' because it uses HTML 5 & CSS3 for mobile UI and JavaScript to communicate with device SDK.
Hybrid app = Single Page Application
Hybrid mobile app is basically a single page application (or SPA). SPA is a web application that lives within a single HTML page. The “views” of the application are injected into- and removed from the DOM as needed as the user navigates through the app. A single page application architecture is particularly well suited for mobile apps:
- The absence of continual page refreshes provides a more fluid / closer to native experience.
- The UI is entirely created at the client-side with no dependency on a server to create the UI, making it an ideal architecture for applications that work offline.
How PhoneGap works?
PhoneGap provides a JavaScript API phonegap-3.0.0.js to mobile app developers. This JavaScript API calls PhoneGap platform specific engine/bridge which in turn calls native platform SDK to perform actions on device. E.g., access the contact list, make a call etc. In case of Windows Phone, a PhoneGap engine/bridge is a Silverlight assembly WP7GapClassLib.dll.
PhoneGap engines are built using the native languages of each platform (C#, Objective-C and Java) which expose interfaces to the JavaScript developer. Most of the communication between PhoneGap JavaScript API and Engine occurs by setting Chrome-less browser URL.
gap:
Figure - PhoneGap application architecture
PhoneGap also provides a build system to bundle HTML 5, JavaScript and CSS3 in a Chrome-less browser i.e., a browser without any user interface.
Figure - Phonegap build system bundles js, CSS, and HTML with Chrome-less browser
Accelerometer
Figure - A US $35 3D Accelerometer from Dimension Engineering
Accelerometer captures device motion in the x, y, and z direction. Using PhoneGap, you can access Accelerometer mounted on iPhone, Android, Windows Phone, and Black Berry. So for example, add following configuration in App/Supporting Files/Cordova.plist to obtain permission to use iOS Accelerometer .
<key>Plugins</key>
<dict>
<key><a href="http://docs.phonegap.com/en/1.9.0/cordova_accelerometer_accelerometer.md.html#Accelerometer">Accelerometer</a></key>
<string>CDVAccelerometer</string>
</dict>
A similar permission for Windows Phone can be obtained using a configuration Properties/WPAppManifest.xml.
<Capabilities>
<Capability Name="ID_CAP_SENSORS" />
</Capabilities>
Figure - Accelerometer detects changes in device orientation.
Figure - iPhone game 'Labyrinth' using Accelerometer.
Mobile Frameworks for Hybrid mobile app development
Although you can write HTML 5, CSS 3 and JavaScript and bundle it with PhoneGap to generate native image for supported platforms but people usually select some kind of mobile framework for hybrid mobile app development. This saves tons of lines of code and lots of time. Some of the popular frameworks are listed below and they vary in terms of features, platform support and adoption by community.
We will see KendoUI Mobile, Sencha Touch and jQuery Mobile in sections below which would give you an idea what is important when selecting a hybrid mobile app framework. We will take a look into other frameworks in later parts of this series.
jQuery Mobile - Hybrid Mobile App Framework
jQuery Mobile is easy to learn mobile framework with large community support and mobile widgets. It does not have a steep learning curve like Sencha Touch ($595) and may be KendoUI mobile ($699). Though there are performance concerns while loading a list view with 50-60 items, as jQuery Mobile app gets sluggish (and even crash mobile browser). Sencha Touch on the other hand could load 200+ items without any performance issues.
jQuery Mobile 1.3.2 consists of JavaScript (147KB), CSS (92KB), images (~6.6MB zip) and uses core jQuery 1.10.2 library (91KB). Size is a concern on a device with limited RAM and CPU power to parse JavaScript. Size effect could be minimized using Google Closure Compiler, minify, or yui compressor which strips off unreachable JavaScript code. We will deal with optimizations in a separate article. For right now let's focus on mobile app frameworks.
Figure - Closure results in much smaller version of the JavaScript code that functions identically to the original
To design jQuery mobile pages, a handy codiqa designer is available at jQuery Mobile. Once page HTML, CSS and JavaScript is designed, it can downloaded in zip form. It may be helpful to remember that jQuery UI (a jQuery widgets library for desktop web apps), can not be used with jQuery Mobile due to CSS conflicts. So all you have are either jQuery Mobile widgets or community built widgets.
Figure - Codiqa to build mobile UI
To draw above login UI, all you need is to write familiar HTML with jQuery CSS and data attributes. data-attribute is HTML 5 feature which let you define as many data- prefixed attributes on elements to 'store any information' and they will not effect on page layout. Note that data-role attribute on <div> makes it a container for label and textbox.
KendoUI Mobile - Hybrid Mobile App Framework
KendoUI mobile is an MVVM based mobile app framework with charting and some really useful mobile widgets that comes at $699. KendoUI supports model binding like Knockout which saves you from writing tons of lines of code.
Figure - KendoUI mobile provides widgets and framework to build hybrid mobile app
To achieve fluid layout for mobile platforms, use KendoUI with layout libraries like Bootstrap or Foundation as it is not a layout library. KendoUI has lower learning curve as compared to Sencha Touch which is all JavaScript, but provides great flexibility and performance with MVC architecture.
KendoUI Hierarchical ListView, ActionSheet and ListView controls provide a great way to list down items while Tablet SplitView control is an excellent way to to show master-detail scenarios on tablets.
Figure - KendoUI mobile ActionSheet control with iPhone theme
Figure - KendoUI mobile ListView control with Windows Phone theme
Figure - KendoUI mobile SplitView control for Tablets with Android theme
KendoUI Mobile theme builder can be used create platform specific themes:
Figure - Kendo UI Mobile Theme Builder
For performance and flexibility reasons, the Kendo UI mobile iOS theme does not use any images. The UI elements are built with CSS effects only so apps look slightly different from an actual iOS application.
KendoUI provides data visualization capabilities by drawing interactive graphs using its dataviz components. To draw graphs, KendoUI automatically detects browser capabilities and use SVG (or VML as fallback). IE6, IE7, and IE8 only support VML; IE9 supports some SVG; the other major browsers support SVG.
Figure - KendoUI mobile dataviz graphs
Sencha Touch - Hybrid Mobile App Framework
Sencha Touch provides ultimate performance at the cost of complexity and steep learning curve. Sencha Touch is MVC and all JavaScript and it may be confusing for a web developer and little less to Java/C# developer. But this learning cost comes with a benifit of massive performance improvement which is questionable in jQuery Mobile apps.
As Sencha Touch was initially targeted for iOS and later added the support for Android, Black Berry and Windows Phone, so you could expect performance will not be same on all platforms.
Sencha Touch has a bag full of mobile widgets like Navigation View & Carousel and a power layout library.
Figure - Sencha Touch Carousel View control
Sencha Touch has native packaging and deploy system just like PhoneGap. So, in a way you could build end-to-end cross platform solution using just Sencha Touch without employing PhoneGap.
HTML 5 Responsive Website
We have already discussed this kind of application development in Part 1. However let's touch couple of more concepts here that are important to mobile website development.
Mobile Browsers
Mobile browsers are different from desktop browsers as they support two Viewports i.e., Layout and Visual. Layout viewport is the one that is used for all CSS calculation while visual viewport is the part of html document currently on device screen. They Layout view port is different in width per browser. Safari iPhone uses 980px, Opera 850px, Android WebKit 800px, and IE 974px. On BlackBerry the layout viewport equals the visual viewport at 100% zoom. This does not change.
window.innerWidth
document.clientWidth
Figure - Mobile browsers support two viewports - Layout and Visual
Hash Fragment
Figure - Hash fragment to index AJAX based Websites
Most mobile website are AJAX based to load contents when needed. In a typical website, URL is a way to bookmark and share contents you like as well as a way for search engines to index your website. However AJAX based websites like Twitter and Facebook download an initial JavaScript which makes AJAX calls to get further contents. The problem with crawlers (like Google) is that they do not parse JavaScript or make AJAX calls and therefore can never see the same page which user see. This results in poorly indexed website.
To create a URL that return HTML snapshot to crawlers instead of JavaScript, hash fragments (i.e., #!) are used. A URL http://twitter.com/#!/mashable or www.example.com/ajax.html#!key=value on AJAX website or single page applications, returns static HTML to crawler which improves site indexing.
What's Next
In the next update of this article, we will explore capabilities of various mobile platforms further. We will also take a look into iOS, Android, WP, and BlackBerry development and write code use device capabilities.