iDev: UIImage and UIImage View

When we use images in our application then we face different type of scenarios while handling the image. Before we go into the scenarios / situations of image handling in Application, let us understand the concept of UIImage and UIImageView.

Concept of UIImage and UIImageView (container)

UIImage – Bitmap with different formats Ex png and jpeg. Recommended format is png.UIImageView – This is an iOS Widget that acts like a container for holding the image. To hold the image, UIImageView is required.

When UIImage is shown in UIImageView, there is a property (Content Mode) of UIImageView, that render the Image in UIImageView. We mostly use three types of Content Mode property. These are:

  • Scale To Fill
  • Aspect Fit
  • Aspect Fill

How these Content Mode render the image we can see by following examples

  • UIImage of size (100×150)
  • UIImageView of size (200×200)

Different Content modes for placing Image in ImageView

1. Scale To Fill

In this case, content is scaled to fill in ImageView with distorted or same aspect ratio. If the image aspect ratio is different than that of container then final image ratio when fitted in the container will be different and hence the image is finally distorted.

(Aspect Ratio is Width / Height)

InnovationM Image Handling in iOS

2. Aspect Fit

In this case, content is scaled to fit in ImageView (container) without changing the aspect ratio of image . Remainder is transparent.

InnovationM Image Handling in iOS

3. Aspect Fill Without Clipping

In this case, image is scaled to fill in ImageView. Aspect ratio of image is not changed.

InnovationM Image Handling in iOS

4. Aspect Fill With Clipping

In this case, content is scaled to fill in ImageView the same way it happen in the above case but then finally image is cropped to the exact size of the ImageView size.

InnovationM Image Handling in iOS

Calculating new width and height with maintaining aspect ratio

Image original width = 100 and height = 150
Container width  = 200 and height = 200

x-ratio = Container width / Image original width = 200/100 = 2.0
y-ratio =  Container height / Image original height = 200/ 150 =  1.33

Selected ratio = min (x-ratio, y-ratio) = 1.33

Final Image width = Image original width * Selected Ratio = 100 * 1.33 = 133
Final Image height = Image original height * Selected Ratio = 150 * 1.33 = 200

Final Image width x height = 133 x 200 (Original width x height of image was 100 x 150)

Showing Images coming from Server (Different Scenarios)

We can use Aspect Fit mode for all the scenarios. It will serve in every scenario if you don’t want to distort image.

Scenario 1
Image width is lesser than Container width.
Image height is lesser than Container height

Image width = 100 and height = 150
UIImageView width = 200 and height = 200

Final Image width = 133  and height = 200 (Refer the calculations above)
Image is scaled up to fit the container.

InnovationM Image Handling in iOS

Scenario 2 
Image width is greater than Container width.
Image height is lesser than Container height

Image width = 100 and height = 150
UIImageView width = 80 and height = 200

Final Image width = 80 and height = 122
Image is scaled down to fit the container.

InnovationM Image Handling in iOS

Scenario 3
Image width is lesser than Container width.
Image height is greater than Container height.

Image width = 100 and height = 150
UIImageView width = 200 and height = 120

Final width = 80  and height = 120
Image is scaled down to fit the container.
InnovationM Image Handling in iOS

Scenario 4
Image width is greater than Container width.
Image height is greater than Container height.

Image width = 100 and height = 150
UIImageView width = 80 and height = 100

Final width = 66  and height = 100
Image is scaled down to fit the container.

InnovationM Image Handling in iOS

Scenario 5 (Same Aspect Ratio of Image and ImageView)
Image width is greater than Container width.
Image height is greater than Container height.

Image width = 100 and height = 150
UIImageView width = 80 and height = 120

Final width = 80 and height = 120
Image is scaled down to fit the container.

InnovationM Image Handling in iOS

Scenario 6 (Same Aspect Ratio of Image and ImageView)
Image width is lesser than Container width.
Image height is lesser than Container height.

Image width = 100 and height = 150
UIImageView width = 120 and height = 180

Final width = 120 and height = 180
Image is scaled up to fit the container.

InnovationM Image Handling in iOS

How we change the image size and compress image file size-

Uploading Images to the Server (Different Scenarios)

Many times we have to upload images in an application from device (iPhone, iPad) to the server. It could be a photo clicked from the camera or there was an old image that we choose and upload from the application.

Before uploading we can do two things with the image:

1. Change the width and height of original image.
2. Compress the image to be of smaller file size.

Let us understand them.

1. Change the width and height of original image.

To resize the image, we have to configure the drawing environment for rendering into a bitmap.

1# UIGraphicsBeginImageContextWithOptions()  method is used to create the bitmap-based graphics context.

This method takes two parameters:

  1. Size of image (changed size) and
  2. Scale factor of device as parameter.

Scale factor for Normal Display = 1.0
Scale factor for Retina Display = 2.0

2# – (void) drawInRect:(CGRect)rect; method is used to draw the image in target rectangle.

3# UIGraphicsGetImageFromCurrentImageContext()  method is used to get the resized image from drawing environment.

4# UIGraphicsEndImageContext() method is used to clean up the bitmap drawing environment and remove the graphics context from the top of the context stack.

Example :

Original source Image  Size = (2448, 3264)
Original source image file size = 3.8 MB

After resizing image to size (1024,768):
Resized source Image  Size = (1024,768)
Resized source image file size = 2.0 MB

Code Example:

2. Compress the image to be of smaller file size.

We can compress the image file size by following method.

UIImageJPEGRepresentation() This method takes two parameter

  1. UIImage object.
  2. Compress ratio (It can be between 0.0 and 1.0)

This method will return NSData representation of image after compressing.

Example :

Original source Image  Size = (2448, 3264)
Original source image file size = 3.8 MB

After compressing image file  size by 0.5:
Resized source Image  Size = (2448, 3264)
Resized source image file size = 534 KB

Code Example:

Depending upon your requirement whether to reduce the size (width and height in pixels) OR reduce the file size OR Both, you may apply the above.

Original Source: Click Here

Advertisements

iDev: Objective-C Associated Objects

Objective-C Associated Objects

Add properties to objects in categories.

As a developer, I love coming across new methods or techniques that help make better, more readable code. Recently I was trying to find a better way of passing information from a method that creates a UIAlertView to the UIAlertView’s delegate method alertView:didDismissWithButtonIndex:. There is no userInfo dictionary for an alert view, and Apple specifically says not to subclass UIAlertView. What I’ve done in the past is create a property or class instance variable to temporarily hold the object I want to pass around. I don’t like this technique, it feels sloppy, but it gets the job done. Now behold the power of Objective-C Associated Objects.

Associated Objects

Associated objects have been around since iOS 3.1 and are a part of the Objective-C runtime. They allow you to associate objects at runtime. Basically, you can attach any object to any other object without subclassing. To begin using associated objects, all you need to do is import <objc/runtime.h> in the class where you want to use them. The relevant methods are the following:

void objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy)
id objc_getAssociatedObject(id object, void *key)
void objc_removeAssociatedObjects(id object)

object is the source object for the association, or in other words, it is the object that will point to the other object.
*key is the the key for the association, this can be any void pointer, anything that has a constant memory address is all you want.
value is the object you want to store or associate with the source object.
policy is a constant defining the type of reference, similar to the types you use when declaring properties. The possible values are:

enum {
   OBJC_ASSOCIATION_ASSIGN = 0,
   OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,
   OBJC_ASSOCIATION_COPY_NONATOMIC = 3,
   OBJC_ASSOCIATION_RETAIN = 01401,
   OBJC_ASSOCIATION_COPY = 01403
};

 

Typically we don’t want to use objc_removeAssociatedObjects, but would rather use setAssociatedObject with a nil value to remove an association. According to Apple,
The main purpose of this function is to make it easy to return an object to a “pristine state”. You should not use this function for general removal of associations from objects, since it also removes associations that other clients may have added to the object. Typically you should use objc_setAssociatedObject with a nil value to clear an association.

In many cases you probably won’t have to worry about removing an association because when the source object is destroyed it will destroy the reference to the associated object.

Sample Use Case

In my case, I want to associate an NSIndexPath to a UIAlertView. Let me explain my use case a little further, you have probably come across a similar problem. I have a table view where I show a confirmation alert when the user tries to delete a row. Usually I wouldn’t put a confirmation on a delete, but sometimes it has serious implications (maybe you’re deleting a folder holding 100 records of something and deleting the folder deletes all those precious records).

The alert is created and displayed in the UITableViewDataSource method tableView:commitEditingStyle:forRowAtIndexPath:. At this point you have the indexPath you want to delete. Once you call -show on the alert, your class starts waiting for the UIAlertViewDelegate callback methodalertView:didDismissWithButtonIndex:. Once the user confirms, it enters the delegate method and you no longer know which indexPath you should delete.

Now I’m going to detail a number of solutions to this problem, each better than the last. I’m only going to show the relevant code though instead of the entire class because I’m using a very simple example. I just slightly modified the code that is generated for you when you create a new project with the master-detail template (without core data).

Original Solution

The original solution was to have a class level instance variable that holds the index path we want to delete. We would set the index path to delete in our commitEditingStyle method, and then retrieve it in alertView:didDismissWithButtonIndex.

 

@interface MasterViewController () <UIAlertViewDelegate> {
    NSMutableArray *_objects;
    NSIndexPath *_indexPathToDelete;
}

...

- (void)tableView:(UITableView *)tableView commitEditingStyle:
(UITableViewCellEditingStyle)editingStyle 
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
    	NSString *deleteMessage = @"Are you sure you want to delete this super important thing?";
        UIAlertView *deleteConfirmation = [[UIAlertView alloc] initWithTitle:@"Delete Row"
                                                                     message:deleteMessage
                                                                    delegate:self
                                                           cancelButtonTitle:@"Cancel"
                                                           otherButtonTitles:@"Confirm", nil];
        _indexPathToDelete = indexPath;
        [deleteConfirmation show];
    }
}

...

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [_objects removeObjectAtIndex:_indexPathToDelete.row];
        [_tableView deleteRowsAtIndexPaths:@[_indexPathToDelete] withRowAnimation:UITableViewRowAnimationFade];
    }
}

 

This solution works, but why would we want to use this instance variable that is visible to the entire class? Only two methods have interest in this index path, and what if some other method messes with indexPathToDelete and we get some unexpected behavior. It would be better if we could confine this object to only the methods that care about it.

Acceptable Solution

Using the objective-c runtime methods we can associate the index path to the alert view. We will set the association in commitEditingStyle, and retrieve the index path in didDismissWithButtonIndex:.

 

#import <objc/runtime.h>

static char deleteKey;

@interface MasterViewController () <UIAlertViewDelegate> {
    NSMutableArray *_objects;
}

...

- (void)tableView:(UITableView *)tableView 
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSString *deleteMessage = @"Are you sure you want to delete this super important thing?";
        UIAlertView *deleteConfirmation = [[UIAlertView alloc] initWithTitle:@"Delete Row"
                                                                     message:deleteMessage
                                                                    delegate:self
                                                           cancelButtonTitle:@"Cancel"
                                                           otherButtonTitles:@"Confirm", nil];
        objc_setAssociatedObject(deleteConfirmation, &deleteKey, indexPath, OBJC_ASSOCIATION_RETAIN);
        [deleteConfirmation show];
    }
}

...

- (void)alertView:(UIAlertView *)alertView 
didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSIndexPath *deletePath = objc_getAssociatedObject(alertView, &deleteKey);
        [_objects removeObjectAtIndex:deletePath.row];
        [_tableView deleteRowsAtIndexPaths:@[deletePath] 
                               withRowAnimation:UITableViewRowAnimationFade];
    }
}

 

As you can see, we no longer need the instance variable, but we use a new static char variable as the association key. The alert view holds a strong reference to the index path, so it persists from one method to the next as long as the alert view is still in memory. When the alert view is destroyed it will also destroy the index path associated with it. This makes the code clearer and confined to just the methods it is used in instead of having an instance variable that is available to the whole class. We can make this code even better though.

Better Solution

Associated Objects Category

You can create a category on NSObject that simplifies the objective-c runtime calls into a nice API you can use in your normal classes. You could expand on this, but a basic category would be as follows:

NSObject+AssociatedObjects.h

@interface NSObject (AssociatedObjects)
- (void)associateValue:(id)value withKey:(void *)key;
- (id)associatedValueForKey:(void *)key;
@end

 

NSObject+AssociatedObjects.m

#import "NSObject+AssociatedObjects.h"
#import <objc/runtime.h>

@implementation NSObject (AssociatedObjects)

- (void)associateValue:(id)value withKey:(void *)key
{
    objc_setAssociatedObject(self, key, value, OBJC_ASSOCIATION_RETAIN);
}

- (id)associatedValueForKey:(void *)key
{
    return objc_getAssociatedObject(self, key);
}

@end

 

Your view controller would then look like this…

 

#import "NSObject+AssociatedObjects.h"
static char deleteKey;

@interface MasterViewController () <UIAlertViewDelegate> {
    NSMutableArray *_objects;
}

...

- (void)tableView:(UITableView *)tableView 
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSString *deleteMessage = @"Are you sure you want to delete this super important thing?";
        UIAlertView *deleteConfirmation = [[UIAlertView alloc] initWithTitle:@"Delete Row"
                                                                     message:deleteMessage
                                                                    delegate:self
                                                           cancelButtonTitle:@"Cancel"
                                                           otherButtonTitles:@"Confirm", nil];
        [deleteConfirmation associateValue:indexPath withKey:&deleteKey];
        [deleteConfirmation show];
    }
}

...

- (void)alertView:(UIAlertView *)alertView 
didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSIndexPath *deletePath = [alertView associatedValueForKey:&deleteKey];
        [_objects removeObjectAtIndex:deletePath.row];
        [_tableView deleteRowsAtIndexPaths:@[deletePath] 
                    withRowAnimation:UITableViewRowAnimationFade];
    }
}

 

I like this a little better because it abstracts out the runtime methods and gives you a nice interface you can use on any object. This accomplishes the same thing, but to me it is much more readable and feels better.

Awesome Solution

According to Apple docs:
The UIAlertView class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified.

Also according to Apple docs:
Categories can be used to declare either instance methods or class methods but are not usually suitable for declaring additional properties. It’s valid syntax to include a property declaration in a category interface, but it’s not possible to declare an additional instance variable in a category. This means the compiler won’t synthesize any instance variable, nor will it synthesize any property accessor methods. You can write your own accessor methods in the category implementation, but you won’t be able to keep track of a value for that property unless it’s already stored by the original class.

The only way to add a traditional property-backed by a new instance variable-to an existing class is to use a class extension, as described in ‘Class Extensions Extend the Internal Implementation.'”

With our newfound power, we will add a new property to UIAlertView without subclassing it. As you see in the documentation, it is perfectly valid to declare a property in the category interface, you just can’t create a new instance variable. We don’t need a new instance variable, we will just override the getter and setter of our property to store and retrieve the property by associating it to the alert view.

Let’s create a category on UIAlertView called DeleteConfirmation.

In UIAlertView+DeleteConfirmation.h

@interface UIAlertView (DeleteConfirmation)
@property (nonatomic) NSIndexPath *indexPathToDelete;
@end

 

Now in UIAlertView+DeleteConfirmation.m

#import "UIAlertView+DeleteConfirmation.h"
#import "NSObject+AssociatedObjects.h"

@implementation UIAlertView (DeleteConfirmation)

- (void)setIndexPathToDelete:(NSIndexPath *)indexPathToDelete
{
    [self associateValue:indexPathToDelete withKey:@selector(indexPathToDelete)];
}

- (NSIndexPath *)indexPathToDelete
{
    return [self associatedValueForKey:@selector(indexPathToDelete)];
}

@end

 

Thanks to Erica Sadun, who then credits Gwynne Raskind, for this bad-assery of using the property selector as the association key. According to them, this is valid because Apple’s selector implementation uses a fixed address.

Using the same example, after importing the new category, our view controller code becomes:

 

#import "UIAlertView+DeleteConfirmation.h"

@interface MasterViewController () <UIAlertViewDelegate> {
    NSMutableArray *_objects;
}

...

- (void)tableView:(UITableView *)tableView
 commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSString *deleteMessage = @"Are you sure you want to delete this super important thing?";
        UIAlertView *deleteConfirmation = [[UIAlertView alloc] initWithTitle:@"Delete Row"
                                                                     message:deleteMessage
                                                                    delegate:self
                                                           cancelButtonTitle:@"Cancel"
                                                           otherButtonTitles:@"Confirm", nil];
        deleteConfirmation.indexPathToDelete = indexPath;
        [deleteConfirmation show];
    }
}

...

- (void)alertView:(UIAlertView *)alertView 
didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSIndexPath *deletePath = alertView.indexPathToDelete;
        [_objects removeObjectAtIndex:deletePath.row];
        [_tableView deleteRowsAtIndexPaths:@[deletePath] 
                            withRowAnimation:UITableViewRowAnimationFade];
    }
}

 

Beautiful. I love it. The index path to delete looks like any other property you would access.

Conclusion

Ok… maybe this is overkill for the example I gave, but I’m sure you will find other uses for it now that you know about it. It is a great weapon to have at your disposal, and it really helps you write much cleaner, self documenting code.

Source Reference : Press Here

iDev: How to extend existing method in Objective-C

Hi Friends,

Todays you learn a very good technique, I hope:)

With blocks it’s more easy if you need extend your method. But if you will need extend some method of another class, not yours, and you will not be able to get the sources then this solution for you. (And if you will not be able or does not have any reason for creating a subclass)

1. You need create a category of class

2. import runtime in implementation file (.m)

#import <objc/runtime.h>

3. implement your method inside category, for example :

– (void) extend_method {

// your code

//  here will be performed the original method
[self extend_method];

// your code
}

It looks like this method has recursive calls itself, but it’s not true. Look next step

4. add method for replace (you can use +initialize or +load)

+ (void) initialize {
Method original = class_getInstanceMethod(self, @selector(method));
Method replacement = class_getInstanceMethod(self, @selector(extend_method));
method_exchangeImplementations(original, replacement);
}

Done!

Reference : Press Here

Keep Coding 🙂

 

iDev: Secure site trust (Https:) in iOS using NSURLConnection

Secure Coding iPhone and iPad Apps Against MiTM

Many iOS applications use HTTP to connect to server side resources. To protect user-data from being eavesdropped, iOS applications often use SSL to encrypt their HTTP connections.

In this article, I will present sample Objective-C code to illustrate how HTTP(S) connections are established and how to locate insecure code that can leave the iOS application vulnerable to Man in the Middle attacks. I will also discuss how to configure an iOS device to allow for interception of traffic through an HTTP proxy for testing purposes.

A Simple App Using NSURLConnection

The easiest way to initiate HTTP requests in iOS is to utilize the NSURLConnection class. Here is sample code from a very simple application that takes in a URL from an edit-box, makes a GET request, and displays the HTML obtained.

[Please note that the code in this particular example is mostly from Apple’s wonderful tutorial on how to use NSURLConnection]

//This IBAction fires when the user types in a URL and presses GO
– (IBAction) urlBarReturn:(id)sender
{   
    //htmlOutput is the UITextView that displays the HTML
    htmlOutput.text=@””;

    //urlBar is the UITextField that contains the URL to load
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:urlBar.text]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                              timeoutInterval:60.0];
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if(!theConnection)
        htmlOutput.text=@”failed”;   
}

– (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{
    //receivedData is of type NSMutableData
    [receivedData setLength:0];

}

– (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];

    NSString *tempString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    htmlOutput.text = [NSString stringWithFormat:@”%@%@”,htmlOutput.text,tempString];

    [tempString release];
}

– (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

    [connection release];

    [receivedData release];

    NSLog(@”Connection failed! Error: %@ %@”,
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);

    htmlOutput.text=[NSString stringWithFormat:@”Connection failed! Error %@ %@”,[error localizedDescription],
                     [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]];
}

– (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@”Succeeded! Received %d bytes of data”,[receivedData length]);

    [connection release];

    [receivedData release];

}

The result is a simple iOS application that fetches HTML code from a given URL.

IOS-app-simple-html
Figure: Simple iOS App using NSURLConnection to fetch HTML from a given URL.

In the screen-shot above, notice that the target URL is https. NSURLConnection seamlessly establishes an SSL connection and fetches the data. If you are reviewing source code of an iOS application for your organization to locate security issues, it makes sense to analyze code that uses NSURLConnection. Make sure you understand how the connections are being inititated, how user input is utilized to construct the connection requests, and if SSL is being used or not. While you are at it, you may also want to watch for NSURL* in general to include invocations to objects of type NSHTTPCookie, NSHTTPCookieStorage, NSHTTPURLResponse, NSURLCredential, NSURLDownload, etc.

Man in the Middle 

74.125.224.49 is one of the IP addresses bound to the host name http://www.google.com. If you browse to https://74.125.224.49, your browser should show you a warning due to the fact that the Common Name field in the SSL certificate presented by the server (www.google.com) does not match the host+domain component of the URL.

IOS-safari-warning Figure: Safari on iOS warning the user due to mis-match of the Common Name field in the certificate.

As presented in the screen-shot above, Safari on iOS does the right thing by warning the user in this situation. Common Name mis-matches and certificates that are not signed by a recognized certificate authority can be signs of a Man in the Middle attempt by a malicious party that is on the same network segment as that of the user or within the network route to the destination.

Ios-NSURL-warning Figure: NSURLConnection’s connection:didFailWithError: delegate is invoked to throw a similar warning.

The screenshot above shows what happens if we attempt to browse to https://74.125.224.49 using our sample App discussed ealier: the connection:didFailWithError: delegate is called indicating an error, which in this case warns the user of the risk and terminates.

This is fantastic. Kudos to Apple for thinking through the security implications and presenting a useful warning message to the user (via NSError).

Unfortunately, it is quite common for application developers to over-ride this protection for various reasons: for example, if the test environment does not have a valid certificate and the code makes it to production. The code below is enough to over-ride this protection outright:

 

– (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace

{
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

– (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge

{
                [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}

The details on this code is available from this stackoverflow post. There is also a private method for NSURLRequest called setAllowsAnyHTTPSCertificate:forHost: that can be used to over-ride the SSL warnings but Apps that use it are unlikely to get through the App store approval process (Apple prohibits invocations of private API).

If you are responsible for reviewing your organization’s iOS code for security vulnerabilities, I highly recommend you watch for such dangerous design decisions that can put your client’s data and your company’s data at risk.

Intercepting HTTPS traffic using an HTTP Proxy.

As part of performing security testing of applications, it is often useful to intercept HTTP traffic being invoked by the application. Applications that use NSURLConnection‘s implementation as-is will reject your local proxy’s self-signed certificate and terminate the connection. You can get around this easily by implanting the HTTP proxy’s self-signed certificate as a trusted certificate on your iOS device [Note: This is not a loop-hole against the precautions mentioned above: in this case we have access to the physical device and are legitimately implatining the self-signed certificate].

If you are using the Burp Proxy or the Charles Proxy, all you need to do is place the self-signed cert on a HTTP location and browse to it. Instructions for the Burp Proxy are available here, and instructions for Charles Proxy are also available.

Once you have your iOS device or simulator setup using the self-signed certificate of your HTTP proxy, you should be able to intercept HTTPS connections that would otherwise terminate. This is useful for fuzzing, analyzing, and testing iOS applications for security issues.

Source Reference : Click Here..

Thanks 🙂

Keep Coding and innovation new thing in your code … 😉

 

iDev : Essential Tools for iOS Developers

75 Essential Tools for iOS Developers

Source Reference : Here

If you were to go to a master woodworker’s shop, you’d invariably find a plethora of tools that he or she uses to accomplish various tasks.

In software it is the same. You can measure a software developer by how they use their tools. Experienced software developers master their tools. It is important to learn your current tools deeply, and be aware of alternatives to fill in gaps where your current ones fall short.

With that in mind, I present to you a gigantic list of tools. Some of these I use daily, others I see potential in. If you have more tools you’d like to see here, just make sure to add a comment.

I tried to categorize these the best I can. Some of the entries are websites, some are back-end services, but most are apps that you install. Not all of the apps are free, so I’ll make a note with a $ to denote that an app costs money.

And without further ado, we’ll start from the beginning of any project, and that

Inspiration

  • pttrns – A great library of iOS screen designs categories by task. If you want to see how other apps handle activity feeds, for instance, this is a great place to go see a bunch of examples.
  • TappGala – Another great collection of nice app designs. It’s not categorized by task, but is just a list of great apps to get inspiration from.
  • Cocoa Controls – A great list of components (code) that you can use in your iOS apps. Sometimes you’ll find great pieces of code that can save you time, other times you can just learn how other developers accomplish certain features. Subscribe to their weekly newsletter; all signal, little noise.
  • IICNS – A collection of really great icons. Get inspired, but don’t copy.
  • Dribbble – Some of the best digital designers post up their work for all to see. A treasure-trove of designs to look at.
  • Capptivate – a gallery of inspirational designs. Some contain animations. Thanks, @joaopmaia!

Design

  • Mocks ($) – An easy to use tool to create a quick mockup of an iOS app. Comes with a bunch of the default controls you can use to assemble something quickly.
  • Briefs ($) – A really useful app that allows you to create a mockup of an app and stitch them together so you can see the interaction. Deploy to a device so you can see what it feels like in your hand.
  • Acorn ($) – A strong competitor to Photoshop, only way cheaper. I find myself reaching for Photoshop less & less these days. Under active development.
  • Sketch ($) – A vector-based drawing tool that is increasingly useful these days, as screen sizes and pixel densities change. It is often helpful to design once and have the freedom to scale up & down as needed. Also sports a really powerful export system. For some example Sketch projects, check out Sketchmine. See my screencast on Sketch for a live demo.
  • iOS 7 PSD by Teehan+Lax – A super handy resource if you (or your designer) uses Photoshop. An iOS 6 version is also available.
  • Bjango’s Photoshop Actions – A definite time-saver if you use Photoshop to design iOS apps. One click access to resize canvases, scale by 200% (or 50%), set global lighting to 90º, and more. Their blog also has a bunch of useful Photoshop workflow tips.
  • xScope ($) – An indespensible swiss-army knife of tools such as guides, pixel loupes, screen rulers, and more. Want to know what color value that pixel is? Want to see how many pixels between a button and the window for a random Mac app? xScope has you covered. Also check out their companion iPhone app for mirroring designs you’re working on and seeing them in pixel-perfect glory on your iDevice.
  • Glyphish ($) – A fantastic collection of high quality icons for your iOS apps. Apple doesn’t provide a lot of built-in icons, so it’s handy to have a collection of icons covering all kinds of various concepts. I’m still looking for a use for that baby icon though. Glyphish comes in packs, and the latest pack has iOS 7 “thin line” icons which will be very handy when designing an iOS 7 app.
  • Fontastic Icons for iOS – An open source set of classes for utilizing icon fonts, such as Font Awesome in your iOS app. Quickly and easily have an icon in whatever pixel dimensions you require. Since fonts by nature can be scaled up and down with ease, this makes a really nice way to ship & use your icons without having to export multiple versions for the sizes you require.
  • PaintCode ($) – A vector-based drawing tool that exports your artwork as the equivalent Core Graphics source code. Awesome for learning how Core Graphics drawing works, but also incredibly handy if you want your drawing to be dynamic. See my screencast on PaintCode for a live demo.
  • Edge Insets ($) – A simple tool that helps you define your edge insets for repeatable images. Available on the Mac App Store.
  • LiveView – A remote screen viewer for iOS, making it easy to immediately see your designs on a device. Thanks, @_funkyboy!
  • Skala Preview ($) – Another excellent tool for quickly showing your designs off on a real device. The guys at Bjango are awesome and this app is deserving of the price. Thanks, jn40!

Source Control

  • Git – If you’re not using source control stop what you’re doing and rectify that. I use git for everything I do and love it.
  • Kaleidoscope ($) – The best diff/merge tool around. Does 3-way merges and is beautiful to look at. I use it every day.
  • p4merge – A free, ugly alternative to Kaleidoscope. Powerful 3-way merge, but good luck finding the download link. It’s hidden deeper in their site every time I look for it.
  • Git X – A simple, powerful GUI tool for visualizing git timelines and quickly & easily staging commits. I usually live in the Terminal for git usage, but fall back to this app when I need to stage hunks of changes into logical commits. This is a fork of the original (abandoned) GitX, which I found on this list of forks.
  • Source Tree – A free, full-featured Git application. I don’t use this because I favor the command line, but if a GUI tool is your cup-o-tea, check this app out.

Dissecting Apps

  • pngcrush – This little utility can crush & uncrush PNG files, which is handy when you want to view images contained in app bundled distributed in the App Store. Just open iTunes, view the local Apps list, and right click on any icon to Show in Finder. Once there, open up the app and you’ll see a bunch of PNG files, but you can’t view them. Using pngcrush you can extract the full version so it can be opened with Preview.
  • appcrush.rb – This handy little ruby script will automate the above process for all images. Just point it to a .app file on your disk and it will extract all the images to a folder on your desktop. Handy for seeing how apps on your phone accomplish certain designs. Check out my screencast on dissecting apps for a live demo.
  • Charles ($, free limited demo) – I don’t know what’s going on with the ugly UI or icon, but Charles is an essential tool for any developer. Charles acts as a proxy to allow you to inspect your network traffic to & from the iPhone Simulator. You can also inspect traffic from your device by setting your phone’s proxy to your Mac running Charles. With self-signed SSL certificates, request & response breakpoints, and request/response viewers, Charles is really amazingly powerful. A must-have tool. Again, my screencast on dissecting apps covers this well.

Editors

I know what you’re thinking, don’t all iOS developers use Xcode? Well mostly, yes. But with my love/hate relationship with Xcode, I believe there is tremendous value in considering alternatives.

  • AppCode – A full-fledged IDE from Jetbrains (makers of the excellent ReSharper for .NET). Immensely powerful refactorings & features that help you write code faster. Quickly identify dead code, automatically insert #import statements when you use related code, easily extract variables, methods, and classes. My only wish for this app is that it would instead be a plugin to Xcode.
  • Vim – Wait, vim? Really? Yes, there are folks who do all their Objective-C development in vim. I’m not one of these, but I am a fan of vim for Ruby development. As such, I’m a huge fan of…
  • Xvim – An Xcode plug-in that gives you vim keybindings. Works well, ‘nuff said.
  • OMColorSense – Another plugin for Xcode, this one gives you a small display of color when your cursor is on a line looking like: [UIColor redColor]. Clicking on this little color tab opens a color picker that you can change, and any change in color you make is reflected in the code by changing the line to [UIColor colorWithRed:… green:… blue:… alpha:… ]. When someone is watching me write code with this enabled, they invariably ask me, “Whoa! What was that?!”
  • KSImageNamed – Another Xcode plug-in, this one allows you to autocompleted image filenames from your bundle when typing [UIImage imageNamed:…]. Great way to avoid the inevitable typo that causes this method to return nil and you to subsequently waste 10 minutes trying to figure out why your images aren’t displaying.
  • CocoaPods Xcode Plugin – This plug-in adds a menu item for interacting with CocoaPods. Useful if you don’t like dropping to the command line.
  • Alcatraz Package Manager – An awesome meta plug-in that allows you to easily install other Xcode color schemes and plug-ins with a single click.
  • Code Runner ($) – a light-weight code-aware text editor that knows how to compile & run code in most languages. Want to test out a quick snippet of Objective-C code and don’t want to create an entire Xcode project to do it? Code Runner to the rescue.

Documentation

Ahhh, documentation, everyone’s favorite topic. Even still, documentation is really important to have, so pay attention so we can make your life easier.

  • appledoc – Want to automatically generate documentation that look’s like Apple’s? Look no further. Automatically inter-links symbols defined in your project as well as extracting discussion to output using specially formatted code-comments. Generates official docsets and HTML web sites.
  • Dash ($) – A must-have API documentation viewer and code snippet manager. This tool is really handy as it allows you to download & search API docs for all kinds of languages & frameworks with lightning speed. The fastest way to get access to the docs. I integrate Dash with Alfred to make searches even faster.

Dependency Management

Yes, there’s only one tool listed here. I didn’t want to include actual 3rd party libraries, as that would be a different list entirely. When it comes to dependency management, there’s only one game in town:

  • CocoaPods – The essential tool for Objective-C projects. Allows you to quickly & easily integrate 3rd party libraries into your application. It does so by creating a second static library project and automatically links this with your projects. There are thousands of pods available, and it’s easy to add support for libraries that you don’t own (or perhaps are private). I use CocoaPods in every single project I work on.

Diagnostics & Debugging

At some point our app is in the field and we need to understand better what’s going on, maybe to fix bugs or to improve performance.

  • Cocoa Lumberjack – a much more powerful NSLog, Cocoa Lumberjack offers advanced logging behaviors such as logging to rotated files, logging to the network, and filtering based on log level (info, debug, warn, error). Covered by NSScreencast Episode 61
  • DCIntrospect – crazy powerful tool that you’d link inside your app when running in debug and on the simulator. Once you do, you can press the spacebar to get some really helpful view debugging support. See exact dimensions of elements on the screen, print out view hierarchies, even nudge views horizontally or vertically.
  • Pony Debugger – another tool you’d use by embedding a library in your debug builds, Pony Debugger actually utilizes Chrome’s dev tools for seeing network requests coming out of the device, as well as a rudimentary Core Data browser. It’s hard to describe, but check out my screencast on Pony Debugger for more info.
  • Runscope ($) – Runscope is a service running online that can capture requests, log details, and give you valuable data about your API. Simple to set up, as it’s an HTTP pass-through API, all you need to change is your host name.
  • SimPholders – Quick, easy access to your simulator folders. Browse by iOS version, then app name and jump right to the folder in Finder.
  • Spark Inspector ($) – Debug your view hierarchy running on your app in debug mode, in 3D. This app really has to be seen to fully understand the value, but it can really help to understand what views are used to compose your app. Also contains a notification center inspector, so you can easily see what NSNotifications are firing and who is observing them. Another app to look at that is similar is Reveal.

Images

  • ImageAlpha – A Mac app that allows you to convert a 24-bit PNG with transparency to an 8-bit PNG with an alpha channel. Typically 8-bit PNGs don’t have an alpha channel, so if your image can be represented in 8-bits (say, a solid color button) you can save a lot on storage by converting the 24-bit PNG to 8-bit using ImageAlpha.
  • ImageOptim – Another Mac app that compresses PNGs in order to save space. Most PNG files can shave off a few % of the size, and sometimes you’ll shrink the files by 30% or more. Smaller images mean smaller app sizes and less memory used to load them at runtime.
  • Prepo – A little Mac app that can quickly resize artwork in all the various sizes you might need. Just drag a large icon file (say, 1024×1024) onto Prepo and watch it spit out 512×512 iTunesArtwork, 114×114 Icon@2x.png, and all the other sizes & filenames you’d expect.
  • Slender ($) – an awesome app that analyzes your app and finds all sorts of problems, such as missing retina artwork, unused images, image that could benefit from compression and more. Shave kilobytes off of your iPhone app by shedding unused images with Slender.

Core Data

  • Mogenerator – still a super useful tool for generating smart subclasses of your NSManagedObjects in your Core Data model. Some use Xcode for this, and resort to manually subclassing or creating categories in order to add logic to the models. Mogenerator runs as a quick pre-compile script to generate subclasses for you to use. It does this by creating an underscored version (_User) and a regular one for you to modify (User).
  • Base ($) – there will come a time when you need to inspect your actual Core Data sqlite database to see what’s going on. You can use the sqlite3 command line tool, but Base offers a nice looking GUI browser. Just don’t vomit when you see the database schema that Core Data created for you.
  • Core Data Editor ($) – for more advanced data anlysis, exploration, and modification you can use Core Data Editor. This app understands Core Data, so you’re working directly with the entities instead of database rows.

Back-end Services

Ultimately your iOS app will likely want to talk to a server to share data, fetch new content, send push notifications or whatever. While this can be accomplished manually, you might want a more drop-in solution.

  • Helios – Helios is an open-source framework that provides essential backend services for iOS apps, from data synchronization and push notifications to in-app purchases and passbook integration. Built on top of many open source ruby gems, so you can pick & choose and build your own stack if you so desire. Take a look at the Nomad CLI set of handy related tools as well.
  • Windows Azure Mobile Services – you can think of this sort of like a programmable database in the cloud. Create tables, run JavaScript on read, insert, delete to add additional functionality. Really easy support for push notifications as well.
  • Urban Airship – I’ve been using Urban Airship to deliver push notifications for a while now. Really easy to integrate with, and small usage is free.
  • Parse – This is another data-in-the-cloud service, but offers an impressive API and online data browser. We use Parse for a really small app and works well for that.

Analytics

There are other players here, but none that I’ve seen have been compelling enough to switch from flurry. I’m open to hearing suggestions, so let’s hear about ‘em in the comments.

  • Flurry – I’ve used flurry for a long time to provide useful analytics on the usage of my apps. Need to know when to stop supporting iOS 5? Flurry gives you the numbers to have a realistic conversation.

Deployment

  • Deploymate ($) – Need to support iOS 4 still, but you’re compiling with the iOS 6 SDK? Deploymate will warn you when you’re using symbols that don’t exist in your deployment target.
  • Cupertino – Part of the Nomad CLI tools, Cupertino gives you command line access to managing devices & profiles in the Apple Provisioning Portal. For example, just type ios devices:list to see the current list of devices in your account. Useful for automating lots of processes.
  • Hockey App ($) – A great service for managing the distribution of your ad-hoc builds. Testers can get a link to install new betas over the air. Also provides robust crash reporting so you can easily respond to crashes in your apps.
  • TestFlight – A free service, similar to Hockey App. We’ve used TestFlight with great success for easily distributing apps and collecting feedback from our users. My only wish is that they’d start charging for the service. Also includes analytics and crash reporting, but we don’t use those features.
  • iOS Simulator Cropper – A really easy way to snap images of the simulator, with or without status bar, with or without device chrome, etc. Great for taking App Store or just general marketing screenshots.
  • Status Magic ($) – Take better app store screenshots. Nothing makes your app look less crappy than an App Store screenshot that includes a low battery, or low signal. Status Magic gives you complete customization over what’s present in your status bar, including removing elements, changing the time to “9:41 AM” like Apple tends to do, and more.
  • Crashlytics – Excellent crash reporting for your apps in the field. Automatically uploads dSYMs on release builds so your crashes are automatically symbolicated and organized for you to focus on the most critical ones.

Testing

I don’t think we as a community focus enough on testing. There are great tools available to us, and most are so easy to use we have no real excuse not to write at least some tests for our apps.

  • Kiwi – A great Rspec-style testing framework for iOS. Built on top of SenTestingKit, so you just type ⌘U to run your specs. Also includes a completely robust mocking & stubbing library as well as assertions.
  • Specta – A light-weight BDD framework very similar to Kiwi, but the expectation syntax has one major benefit over Kiwi: everything is implicitly boxed like this: expect(items.count).to.equal(5). There’s no need to wrap 5 in an NSNumber like Kiwi does. Use in conjunction with Expecta for a bunch of useful matchers.

The following are all various ways of performing end-to-end acceptance tests. These tests will actually interact with your interface, touching buttons, scrolling, etc. By nature these will be slower and more brittle, but testing in broad strokes is certainly helpful to see if all of the pieces fit together properly.

Demos / Marketing

  • Reflector ($) – Wirelessly mirror your iOS device on your Mac using Air Play. Great for doing demos of applications on your computer.
  • Placeit – A great collection of high res photos of people using devices, but the screens are templates that you can insert your own screenshots into. Very cool, and great for displaying your app in a nice way on your website.

App Sales Reporting

Of course you want to be able to see how much money you’re making on your app, right? There are a few solutions for this, but here are a couple that work well:

  • App Viz 2 ($) – a really useful Mac app for tracking sales of your apps. You run it locally and it logs in and downloads your sales reports.
  • App Annie – an online sales reporting tool. I’m less comfortable giving my credentials to iTunes to a 3rd party, but it does keep the reports up to date for you so you don’t have to run an app locally. In the comments, Josh Brown suggests creating a different user for analytics in iTunes Connect, which is a really good idea.

Grab Bag

These tools don’t have a defined category above, but deserve a mention nonetheless.

  • Quick Radar – Submitting bug reports to Apple is our only way of making their tools better. If you’re frustrated by the lack of a feature, you should be submitting a bug report. If you come across a bug, you should be submitting a bug report. One has no right to complain if they have not yet filed a radar :). With that in mind, submitting bug reports via bugreporter feels like a trip back to 1995. Quick Radar is an awesome little app that makes submitting bug reports super easy. Sports automatic posting to open radar so others can see it, in addition to tweeting, and posting to App.net. I use this app several times per week.

Thanks 🙂

Keep Reading and Experiment on your code….

 

iDev: UISearchBar Tricks – Showing The Cancel And The Scope Bar Only When Editing

UISearchBar Tricks – Showing The Cancel And The Scope Bar Only When Editing

While working on a particular UISearchBar I ran into 2 little problems, both easy to fix but I thought of posting them in case someone is stuck. What I needed was to make the cancel button and the scope bar to be displayed only while editing. I believe that this should be a pretty common thing to do, and the first part is pretty straight forward:

– (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {

searchBar.showsCancelButton = YES;

return YES;

}

– (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {

searchBar.showsCancelButton = NO;

return YES:

}

That is pretty simple, specially if you don’t forget to associate the UISearchBar’s delegate!

Next, I tried the same with the scope bar but it didn’t work – the scope bar wouldn’t appear. During my testing, I tried to start with the scope bar displayed and then hiding it after the first edit… it worked but when disappearing the search bar would preserve the height as if it was still showing the scope bar!

The final solution is a simple call to [searchBar sizeToFit] and everything works as smooth as it should. Here is the complete code with the small bonus of animating the cancel button’s (dis)appearance:

– (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {

searchBar.showsScopeBar = YES;

[searchBar sizeToFit];

[searchBar setShowsCancelButton:YES animated:YES];

return YES;

}

– (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {

searchBar.showsScopeBar = NO;

[searchBar sizeToFit];

[searchBar setShowsCancelButton:NO animated:YES];

return YES;

}

iPhonegap: Developing a PhoneGap Application

Tutorial: Developing a PhoneGap Application

Reference : Here

In this tutorial, you create a fully functional employee directory application with PhoneGap. You will learn:

  • How to use different local data storage strategies.
  • How to use several PhoneGap APIs such as Geolocation, Contacts, and Camera.
  • How to handle specific mobile problems such as touch events, scrolling, styling, page transitions, etc.
  • How to build an application using a single page architecture and HTML templates.
  • How to build (compile and package) an application for 6 platforms using PhoneGap Build.

To complete this tutorial, all you need is a code editor, a modern browser, and a connection to the Internet. A working knowledge of HTML and JavaScript is assumed, but you don’t need to be a JavaScript guru.

Setting Up

  1. Download the assets for the workshop here.
  2. Unzip the file anywhere on your file system.
  3. If your code editor allows you to “open a directory”, open the phonegap-workshop-master directory.
  4. Follow the instructions below.
Step-by-step solution files are also available here.

Part 1: Choosing a Local Storage Option


Step 1: Explore different persistence mechansisms

Open the following files in phonegap-workshop-master/js/storage, and explore the different persistence stores they define:

  1. memory-store.js (MemoryStore)
  2. ls-store.js (LocalStorageStore)
  3. websql-store.js (WebSqlStore)

Step 2: Test the application with different persistence mechanisms

To change the local persistence mechanism for the application:

  1. In index.html: add a script tag for the corresponding .js file: memory-store.jsls-store.js, or websql-store.js.
  2. In js/main.js: Instantiate the specific store in the initialize() function of the app object: MemoryStoreLocalStorageStore, or WebSqlStore.
  3. To test the application, open index.html in your browser, or simply double-click index.html on your file system. Type a few characters in the search box to search employees by name. Clicking an employee link doesn’t produce any result at this time.

Part 2: Building with PhoneGap Build


  1. If you don’t already have one, create an account on http://build.phonegap.com.
  2. Click the “new app” button to create a new application on PhoneGap Build.
  3. Either point to a GitHub repository where you push your code for this workshop, or zip up your phonegap-workshop directory and upload it to PhoneGap Build.
  4. Click the Ready to build button.
    The iOS button will immediately turn red because the iOS build requires that you upload your Apple Developer certificate and an application provisioning profile. You can find more information here if you haven’t already signed up for the Apple Developer Program. If you don’t have an iOS device, or if you are not ready to upload your developer certificate, you can skip step 5 and keep running the application in the browser or a non iOS device.
  5. To upload your Apple developer certificate and your application provisioning profile:
    • Click the red iOS button.
    • Select “add a key” in the “No key selected” dropdown.
    • Provide a title for your developer certificate/provisioning profile combination (for example: EmployeeDirectory), select your developer certificate and provisioning profile, enter your developer certificate password, and click “submit key”.
    • Go back to the list of apps. Click the iOS button for your application again. Select your newly added key in the iOS dropdown. The iOS build will start automatically.
  6. When the build process completes, use a QR Code reader app to install the Employee Directory application on your device.

To fine tune your build preferences:

  1. In the phonegap-workshop directory, create a file namedconfig.xml file defined as follows (make the necessary adjustments for id, author, etc.):
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    <?xml version="1.0" encoding="UTF-8"?>
    <widget xmlns       = "http://www.w3.org/ns/widgets"
            xmlns:gap   = "http://phonegap.com/ns/1.0"
            id          = "org.coenraets.employeedirectory"
            versionCode = "10"
            version     = "1.1.0">
        <name>Employee Directory</name>
        <description>
            A simple employee directory application
        </description>
        <author href="http://coenraets.org" email="ccoenraets@gmail.com">
            Christophe Coenraets
        </author>
        <feature name="http://api.phonegap.com/1.0/camera"/>
        <feature name="http://api.phonegap.com/1.0/contacts"/>
        <feature name="http://api.phonegap.com/1.0/file"/>
        <feature name="http://api.phonegap.com/1.0/geolocation"/>
        <feature name="http://api.phonegap.com/1.0/media"/>
        <feature name="http://api.phonegap.com/1.0/network"/>
    </widget>
  2. If you used the GitHub approach, sync with GitHub and click the Update Code button in PhoneGap Build.
    If you used the zip file approach, zip up your phonegap-workshop directory and upload the new version to PhoneGap Build
There are many other parameters you can specify in config.xml to configure the build process. See the documentation for config.xmlhere.

Part 3: Using Native Notification


A default webview alert gives away the fact that your application is not native. In this section, we set up the basic infrastructure to display native alerts when the application is running on a device, and fall back to default browser alerts when running in the browser.

  1. In index.html, add the following script tag (as the first script tag at the bottom of the body):
    1
    <script src="phonegap.js"></script>

    This instructs PhoneGap Build to inject a platform specific version of phonegap.js at build time. In other words, phonegaps.js doesn’t need to be (and shouldn’t be) present in your project folder.

  2. In main.js, define a function named showAlert() inside the app object. If navigator.notification is available, use its alert() function. Otherwise, use the default browser alert() function.
    1
    2
    3
    4
    5
    6
    7
    showAlert: function (message, title) {
        if (navigator.notification) {
            navigator.notification.alert(message, null, title, 'OK');
        } else {
            alert(title ? (title + ": " + message) : message);
        }
    },
  3. Test the notification logic by displaying a message when the application store has been initialized: Pass an anonymous callback function as an argument to the constructor of the persistence store (the store will call this function after it has successfully initialized). In the anonymous function, invoke the showAlert() function.
    1
    2
    3
    4
    5
    6
    7
    initialize: function() {
        var self = this;
        this.store = new MemoryStore(function() {
            self.showAlert('Store Initialized', 'Info');
        });
        $('.search-key').on('keyup', $.proxy(this.findByName, this));
    }
  4. Test the application: When you run the application in the browser, you should see a standard browser alert. When you run the application on your device, you should see a native alert.

Part 4: Setting Up a Single Page Application


A single page application 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.

In this section, we set up the basic infrastructure to turn Employee Directory into a single page application.

  1. In index.html: remove the HTML markup inside the body tag (with the exception of the script tags).
  2. In main.js, define a function named renderHomeView() inside the app object. Implement the function to programmatically add the Home View markup to the body element.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    renderHomeView: function() {
        var html =
                "<div class='header'><h1>Home</h1></div>" +
                "<div class='search-view'>" +
                "<input class='search-key'/>" +
                "<ul class='employee-list'></ul>" +
                "</div>"
        $('body').html(html);
        $('.search-key').on('keyup', $.proxy(this.findByName, this));
    },
  3. Modify the initialize() function of the app object. In the anonymous callback function of the store constructor, call the renderHomeView() function to programmatically display the Home View.
    1
    2
    3
    4
    5
    6
    initialize: function() {
        var self = this;
        this.store = new MemoryStore(function() {
            self.renderHomeView();
        });
    }

Part 5: Using Handlebar Templates


Writing HTML fragments in JavaScript and programmatically inserting them into the DOM is tedious. It makes your application harder to write and harder to maintain. HTML templates address this issue by decoupling the UI definition (HTML markup) from your code. There are a number of great HTML template solutions: Mustache.js, Handlebar.js, and Underscore.js to name a few.

In this section, we create two templates to streamline the code of the Employee Directory application. We use Handlebar.js but the smae result can be achieved using the other HTML template solutions.

Modify index.html as follows:

  1. Add a script tag to include the handlebar.js library:
    1
    <script src="lib/handlebars.js"></script>
  2. Create an HTML template to render the Home View. Add this script tag as the first child of the body tag:
    1
    2
    3
    4
    5
    <script id="home-tpl" type="text/x-handlebars-template">
        <div class='header'><h1>Home</h1></div>
        <div class='search-bar'><input class='search-key' type="text"/></div>
        <ul class='employee-list'></ul>
    </script>
  3. Create an HTML template to render the employee list items. Add this script tag immediately after the previous one:
    1
    2
    3
    4
    5
    <script id="employee-li-tpl" type="text/x-handlebars-template">
        {{#.}}
        <li><a href="#employees/{{this.id}}">{{this.firstName}} {{this.lastName}}<br/>{{this.title}}</a></li>
        {{/.}}
    </script>

Modify main.js as follows:

  1. In the initialize() function of the app object, add the code to compile the two templates defined above:
    1
    2
    this.homeTpl = Handlebars.compile($("#home-tpl").html());
    this.employeeLiTpl = Handlebars.compile($("#employee-li-tpl").html());
  2. Modify renderHomeView() to use the homeTpl template instead of the inline HTML:
    1
    2
    3
    4
    renderHomeView: function() {
        $('body').html(this.homeTpl());
        $('.search-key').on('keyup', $.proxy(this.findByName, this));
    },
  3. Modify findByName() to use the employeeLiTpl template instead of the inline HTML:
    1
    2
    3
    4
    5
    6
    findByName: function() {
        var self = this;
        this.store.findByName($('.search-key').val(), function(employees) {
            $('.employee-list').html(self.employeeLiTpl(employees));
        });
    },
  4. Test the application.

Part 6: Creating a View Class


It’s time to provide our application with some structure. If we keep adding all the core functions of the application to the app object, it will very quickly grow out of control. In this section we create a HomeView object that encapsulates the logic to create and render the Home view.

Step 1: Create the HomeView Class

  1. Create a file called HomeView.js in the js directory, and define a HomeView class implemented as follows:
    1
    2
    3
    4
    var HomeView = function(store) {
    }
  2. Add the two templates as static members of HomeView.
    1
    2
    3
    4
    5
    6
    7
    var HomeView = function(store) {
    }
    HomeView.template = Handlebars.compile($("#home-tpl").html());
    HomeView.liTemplate = Handlebars.compile($("#employee-li-tpl").html());
  3. Define an initialize() function inside the HomeView class. Define a div wrapper for the view. The div wrapper is used to attach the view-related events. Invoke the initialize() function inside the HomeView constructor function.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    var HomeView = function(store) {
        this.initialize = function() {
            // Define a div wrapper for the view. The div wrapper is used to attach events.
            this.el = $('<div/>');
            this.el.on('keyup', '.search-key', this.findByName);
        };
        this.initialize();
    }
    HomeView.template = Handlebars.compile($("#home-tpl").html());
    HomeView.liTemplate = Handlebars.compile($("#employee-li-tpl").html());
  4. Move the renderHomeView() function from the app object to the HomeView class. To keep the view reusable, attach the html to the div wrapper (this.el) instead of the document body. Because the function is now encapsulated in the HomeView class, you can also rename it from renderHomeView() to just render().
    1
    2
    3
    4
    this.render = function() {
        this.el.html(HomeView.template());
        return this;
    };
  5. Move the findByName() function from the app object to the HomeView class.
    1
    2
    3
    4
    5
    this.findByName = function() {
        store.findByName($('.search-key').val(), function(employees) {
            $('.employee-list').html(HomeView.liTemplate(employees));
        });
    };

Step 2: Using the HomeView class

  1. In index.html, add a script tag to include HomeView.js (just before the script tag for main.js):
    1
    <script src="js/HomeView.js"></script>
  2. Remove the renderHomeView() function from the app object.
  3. Remove the findByName() function from the app object.
  4. Modify the initialize function() to display the Home View using the HomeView class:
    1
    2
    3
    4
    5
    6
    initialize: function() {
        var self = this;
        this.store = new MemoryStore(function() {
            $('body').html(new HomeView(self.store).render().el);
        });
    }

Part 7: Adding Styles and Touch-Based Scrolling


Step 1: Style the Application

  1. Add the Source Sans Pro font definition to the head of index.html
    1
    <script src="css/source-sans-pro.js"></script>

    Source Sans Pro is part of the free Adobe Edge Web Fonts.

  2. Add styles.css to the head of index.html
    1
    <link href="css/styles.css" rel="stylesheet">
  3. In index.html, modify the home-tpl template: change the search-key input type from text to search.
  4. Test the application. Specifically, test the list behavior when the list is bigger than the browser window (or the screen)

Step 2: Native Scrolling Approach

  1. Modify the home-tpl template in index.html. Add a div wrapper with a scroll class around the ul element with a scroll:
    1
    2
    3
    4
    5
    <script id="home-tpl" type="text/x-handlebars-template">
        <div class='header'><h1>Home</h1></div>
        <div class='search-bar'><input class='search-key' type="search"/></div>
        <div class="scroll"><ul class='employee-list'></ul></div>
    </script>
  2. Add the following class definition to css/styles.css:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    .scroll {
        overflow: auto;
        -webkit-overflow-scrolling: touch;
        position: absolute;
        top: 84px;
        bottom: 0px;
        left: 0px;
        right: 0px;
    }
If the platforms you target support touch-based scrolling of fixed regions, this approach is all you need (you can skip step 3 below). If not, you’ll need to implement a programmatic approach, typically with the help of a library such as iScroll.

Step 3: iScroll Approach

  1. Add a script tag to include the iscroll.js library:
    1
    <script src="lib/iscroll.js"></script>
  2. In HomeView.js, modify the findByName() function: Instantiate an iScroll object to scroll the list of employees returned. If the iScroll object already exists (), simply refresh it to adapt it to the new size of the list.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    this.findByName = function() {
        store.findByName($('.search-key').val(), function(employees) {
            $('.employee-list').html(HomeView.liTemplate(employees));
            if (self.iscroll) {
                console.log('Refresh iScroll');
                self.iscroll.refresh();
            } else {
                console.log('New iScroll');
                self.iscroll = new iScroll($('.scroll', self.el)[0], {hScrollbar: false, vScrollbar: false });
            }
        });
    };
More information on iScroll is available here.

Part 8: Highlighting Tapped or Clicked UI Elements


  1. In styles.css, add a tappable-active class definition for tapped or clicked list item links. The class simply highlights the item with a blue background:
    1
    2
    3
    4
    li>a.tappable-active {
        color: #fff;
        background-color: #4286f5;
    }
  2. In main.js, define a registerEvents() function inside the app object. Add a the tappable_active class to the selected (tapped or clicked) list item:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    registerEvents: function() {
        var self = this;
        // Check of browser supports touch events...
        if (document.documentElement.hasOwnProperty('ontouchstart')) {
            // ... if yes: register touch event listener to change the "selected" state of the item
            $('body').on('touchstart', 'a', function(event) {
                $(event.target).addClass('tappable-active');
            });
            $('body').on('touchend', 'a', function(event) {
                $(event.target).removeClass('tappable-active');
            });
        } else {
            // ... if not: register mouse events instead
            $('body').on('mousedown', 'a', function(event) {
                $(event.target).addClass('tappable-active');
            });
            $('body').on('mouseup', 'a', function(event) {
                $(event.target).removeClass('tappable-active');
            });
        }
    },
  3. Invoke the registerEvents() function from within the app object’s initialize() function.
  4. Test the application.

Part 9: View Routing


In this section, we add an employee details view. Since the application now has more than one view, we also add a simple view routing mechanism that uses the hash tag to determine whether to display the home view or the details view for a specific employee.

Step 1: Create the employee template

Open index.html and add a template to render a detailed employee view:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script id="employee-tpl" type="text/x-handlebars-template">
    <div class='header'><a href='#' class="button header-button header-button-left">Back</a><h1>Details</h1></div>
    <div class='details'>
        <img class='employee-image' src='img/{{firstName}}_{{lastName}}.jpg' />
        <h1>{{firstName}} {{lastName}}</h1>
        <h2>{{title}}</h2>
        <span class="location"></span>
        <ul>
            <li><a href="tel:{{officePhone}}">Call Office<br/>{{officePhone}}</a></li>
            <li><a href="tel:{{cellPhone}}">Call Cell<br/>{{cellPhone}}</a></li>
            <li><a href="sms:{{cellPhone}}">SMS<br/>{{cellPhone}}</a></li>
        </ul>
    </div>
</script>

Step 2: Create the EmployeeView class

  1. Create a file called EmployeeView.js in the js directory, and define an EmployeeView class implemented as follows:
    1
    2
    3
    4
    var EmployeeView = function() {
    }
  2. Add the template as a static member of EmployeeView.
    1
    2
    3
    4
    5
    6
    var EmployeeView = function() {
    }
    EmployeeView.template = Handlebars.compile($("#employee-tpl").html());
  3. Define an initialize() function inside the HomeView class. Define a div wrapper for the view. The div wrapper is used to attach the view related events. Invoke the initialize() function inside the HomeView constructor function.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    var EmployeeView = function(employee) {
        this.initialize = function() {
            this.el = $('<div/>');
        };
        this.initialize();
     }
    EmployeeView.template = Handlebars.compile($("#employee-tpl").html());
  4. Define a render() function implemented as follows:
    1
    2
    3
    4
    this.render = function() {
        this.el.html(EmployeeView.template(employee));
        return this;
    };
  5. In index.html, add a script tag to include EmployeeView.js (just before the script tag for main.js):
    1
    <script src="js/EmployeeView.js"></script>

Step 3: Implement View Routing

  1. In the app’s initialize() function, define a regular expression that matches employee details urls.
    1
    this.detailsURL = /^#employees\/(\d{1,})/;
  2. In the app’s registerEvents() function, add an event listener to listen to URL hash tag changes:
    1
    $(window).on('hashchange', $.proxy(this.route, this));
  3. In the app object, define a route() function to route requests to the appropriate view:
    • If there is no hash tag in the URL: display the HomeView
    • If there is a has tag matching the pattern for an employee details URL: display an EmployeeView for the specified employee.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    route: function() {
        var hash = window.location.hash;
        if (!hash) {
            $('body').html(new HomeView(this.store).render().el);
            return;
        }
        var match = hash.match(app.detailsURL);
        if (match) {
            this.store.findById(Number(match[1]), function(employee) {
                $('body').html(new EmployeeView(employee).render().el);
            });
        }
    }
  4. Modify the initialize() function to call the route() function:
    1
    2
    3
    4
    5
    6
    7
    8
    initialize: function() {
        var self = this;
        this.detailsURL = /^#employees\/(\d{1,})/;
        this.registerEvents();
        this.store = new MemoryStore(function() {
            self.route();
        });
    }
  5. Test the application.

Part 10: Using the Location API


In this section, we add the ability to tag an employee with his/her location information. In this sample application, we display the raw information (longitude/latitude) in the employee view. In a real-life application, we would typically save the location in the database as part of the employee information and show it on a map.

The code below works when running the application as a PhoneGap app on your device. It should also work in Chrome on the desktop when the page is served with the http:// protocol, and in Firefox, regardless of the protocol (http:// or file://).
  1. In index.html, add the following list item to the employee-tpl template:
    1
    <li><a href="#" class="add-location-btn">Add Location</a></li>
  2. In the initialize() function of EmployeeView, register an event listener for the click event of the Add Location list item:
    1
    this.el.on('click', '.add-location-btn', this.addLocation);
  3. In EmployeeView, define the addLocation event handler as follows:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    this.addLocation = function(event) {
        event.preventDefault();
        console.log('addLocation');
        navigator.geolocation.getCurrentPosition(
            function(position) {
                $('.location', this.el).html(position.coords.latitude + ',' + position.coords.longitude);
            },
            function() {
                alert('Error getting location');
            });
        return false;
    };
  4. Test the Application

Part 11: Using the Contacts API


In this section, we use the PhoneGap Contacts API to provide the user with the ability to add an employee to the device’s contact list.

The code below only works when running the application on your device as a PhoneGap app. In other words, you can’t test it in a browser on the desktop.
  1. In index.html, add the following list item to the employee template:
    1
    <li><a href="#" class="add-contact-btn">Add to Contacts</a></li>
  2. In the initialize() function of EmployeeView, register an event listener for the click event of the Add to Contacts list item:
    1
    this.el.on('click', '.add-contact-btn', this.addToContacts);
  3. In EmployeeView, define the addToContacts event handler as follows:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    this.addToContacts = function(event) {
        event.preventDefault();
        console.log('addToContacts');
        if (!navigator.contacts) {
            app.showAlert("Contacts API not supported", "Error");
            return;
        }
        var contact = navigator.contacts.create();
        contact.name = {givenName: employee.firstName, familyName: employee.lastName};
        var phoneNumbers = [];
        phoneNumbers[0] = new ContactField('work', employee.officePhone, false);
        phoneNumbers[1] = new ContactField('mobile', employee.cellPhone, true); // preferred number
        contact.phoneNumbers = phoneNumbers;
        contact.save();
        return false;
    };
  4. Test the Application

Part 12: Using the Camera API


In this section, we use the PhoneGap Camera API to provide the user with the ability to take a picture of an employee, and use that picture as the employee’s picture in the application. We do not persist that picture in this sample application.

The code below only works when running the application on your device as a PhoneGap app. In other words, you can’t test it in a browser on the desktop.
  1. In index.html, add the following list item to the employee template:
    1
    <li><a href="#" class="change-pic-btn">Change Picture</a></li>
  2. In the initialize() function of EmployeeView, register an event listener for the click event of the Change Picture list item:
    1
    this.el.on('click', '.change-pic-btn', this.changePicture);
  3. In EmployeeView, define the changePicture event handler as follows:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    this.changePicture = function(event) {
        event.preventDefault();
        if (!navigator.camera) {
            app.showAlert("Camera API not supported", "Error");
            return;
        }
        var options =   {   quality: 50,
                            destinationType: Camera.DestinationType.DATA_URL,
                            sourceType: 1,      // 0:Photo Library, 1=Camera, 2=Saved Photo Album
                            encodingType: 0     // 0=JPG 1=PNG
                        };
        navigator.camera.getPicture(
            function(imageData) {
                $('.employee-image', this.el).attr('src', "data:image/jpeg;base64," + imageData);
            },
            function() {
                app.showAlert('Error taking picture', 'Error');
            },
            options);
        return false;
    };
  4. Test the Application

Part 13: Sliding Pages with CSS Transitions


  1. Add the following classes to styles.css:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    .page {
        position: absolute;
        width: 100%;
        height: 100%;
        -webkit-transform:translate3d(0,0,0);
    }
    .stage-center {
        top: 0;
        left: 0;
    }
    .stage-left {
        left: -100%;
    }
    .stage-right {
        left: 100%;
    }
    .transition {
        -moz-transition-duration: .375s;
        -webkit-transition-duration: .375s;
        -o-transition-duration: .375s;
    }
  2. Inside the app object, define a slidePage() function implemented as follows:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    slidePage: function(page) {
        var currentPageDest,
            self = this;
        // If there is no current page (app just started) -> No transition: Position new page in the view port
        if (!this.currentPage) {
            $(page.el).attr('class', 'page stage-center');
            $('body').append(page.el);
            this.currentPage = page;
            return;
        }
        // Cleaning up: remove old pages that were moved out of the viewport
        $('.stage-right, .stage-left').not('.homePage').remove();
        if (page === app.homePage) {
            // Always apply a Back transition (slide from left) when we go back to the search page
            $(page.el).attr('class', 'page stage-left');
            currentPageDest = "stage-right";
        } else {
            // Forward transition (slide from right)
            $(page.el).attr('class', 'page stage-right');
            currentPageDest = "stage-left";
        }
        $('body').append(page.el);
        // Wait until the new page has been added to the DOM...
        setTimeout(function() {
            // Slide out the current page: If new page slides from the right -> slide current page to the left, and vice versa
            $(self.currentPage.el).attr('class', 'page transition ' + currentPageDest);
            // Slide in the new page
            $(page.el).attr('class', 'page stage-center transition');
            self.currentPage = page;
        });
    },
  3. Modify the route() function as follows:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    route: function() {
        var self = this;
        var hash = window.location.hash;
        if (!hash) {
            if (this.homePage) {
                this.slidePage(this.homePage);
            } else {
                this.homePage = new HomeView(this.store).render();
                this.slidePage(this.homePage);
            }
            return;
        }
        var match = hash.match(this.detailsURL);
        if (match) {
            this.store.findById(Number(match[1]), function(employee) {
                self.slidePage(new EmployeeView(employee).render());
            });
        }
    },

    Thanks , Keep Coding 🙂

iDev : Experiments with precise timing in iOS

Experiments with precise timing in iOS

iOS is by no means a realtime operating system, but I’m aware that NSTimer and NSObject’sperformSelector:withObject:afterDelay: mechanism aren’t particularly accurate, and I was curious to see whether I could do better.

Hands up, backing away

Disclaimer: I am not at all an expert in realtime programming, or Mach, or iOS-device optimisation, so this is pretty much a fumble in the dark. I won’t be at all offended if anyone wishes to shoot me down and offer a more sensible solution — in fact, please do! Until then, watch as I stumble on…

Also note that there are often ways to eliminate the need for precise timing of this nature, by architecting code appropriately — when it comes to audio, for example, CoreAudio provides a very accurate time base in render callbacks. For things like metronomes or audio synthesizers, it’s always better to establish a starting time, and use the difference between the current time and the starting time in order to determine state, rather than using a timer to advance the state. Still, sometimes, you just need a timer…

What the blazes?

So, I’m working on an update to Loopy, which uses a shared clock object to synchronise tracks and a variety of events (like user interface updates or timed track manipulations). A tester noted that the mute/unmute quantisation feature that I’ve recently implemented, which will mute or unmute a loop at its starting point (rather than whenever you tap it), tends to overshoot a little, resulting in a small part of the beginning of the loop being audible.

Of course, there are other solutions to this particular problem (like stopping or starting playback from the audio render callback, and using Core Audio’s timestamps for exact timing), but I use timers in other places outside Core Audio’s domain, which makes Core Audio’s timing mechanism unavailable, and I wanted to see how accurate I could get the timing.

Our friend, mach_wait_until

I read in several places mention of the Mach API utility mach_wait_until (frommach/mach_time.h), which is very low-level and supposedly fairly accurate. So, based on that lead, I put together an Objective-C singleton class that launches a high-priority thread, and uses said thread to schedule events.

An NSArray of events are maintained, and a scheduleAction:target:inTimeInterval: routine creates and adds events to this array, then pokes the thread.

The thread grabs the next event in sequence, then uses mach_wait_until to sleep until the time of the next event arrives, then performs the specified action on the target. It’s kinda a DIY NSRunLoop.

Here’s a comparison between this technique, and just usingperformSelector:withObject:afterDelay: (which schedules a timer on the NSRunLoop), observed while performing various scheduled events within Loopy running on my iPhone 4 with the debugger, and derived by comparing the time of event execution with the event’s scheduled time:

Mechanism Average discrepancy Minimum discrepancy Maximum discrepancy
NSRunLoop 16.9ms 0.25ms 153.7ms
TPPreciseTimer 5.5ms 0.033ms 72.0ms

That was attempt number 1: This seems to give us about 11.4ms better accuracy on average (three times more accurate).

Not bad, but it turns out mach_wait_until isn’t really that accurate, particularly if there’s a bunch of other stuff going on in other threads.

Spinning, for fun and profit

For my second attempt, the thread performs a mach_wait_until until just before the event is due, then performs a spin lock until the time arrives, using mach_absolute_time to compare the current time with the target time.

This gave further improved results — here’s that table again, but with the new scheme added, with a few different spin lock times:

Mechanism Average discrepancy Minimum discrepancy Maximum discrepancy
NSRunLoop 16.9ms 0.25ms 153.7ms
TPPreciseTimer (original) 5.5ms 0.033ms 72.0ms
TPPreciseTimer (10ms spinlock) 6.0ms 0.002ms 76.5ms
TPPreciseTimer (100ms spinlock) 3.7ms 0.002ms 44.8ms
TPPreciseTimer (200ms spinlock) 2.91ms 0.002ms 74.1ms

It appears that the more stuff there is going on in other threads, the more likely themach_absolute_time call is to overshoot. So, the more time spent in the spin lock, the more leeway mach_absolute_time has to wait too long. Of course, that’s at the cost of making the CPU twiddle its thumbs for the duration.

Better than a punch in the knee

The results weren’t quite as fantastic as I’d hoped — still within the same order of magnitude, that’s for sure — but the average case for the 200ms spinlock approach is 14ms, or 5.8 times, more accurate than the traditional approach, and the minimum case is dramatically better.

You know, I think if I was aware of the results in advance, I might not bother, but I’ll stick with my hard-won 14ms now that I’m here (that’s 617 audio samples, I’ll have you know).

If anyone’s curious about the implementation (or wants to take a stab at doing better), here it is, along with a wildly simplistic commandline test app: TPPreciseTimer.zip

Now to get back to some real work.

Addendum: GCD follow-up

Chris in the comments below suggested trying a GCD-based approach, using dispatch_after. Curious, I rigged it up, and these are the stats, collected the same way as above, added to the prior table:

Mechanism Average discrepancy Minimum discrepancy Maximum discrepancy
NSRunLoop 16.9ms 0.25ms 153.7ms
TPPreciseTimer (original) 5.5ms 0.033ms 72.0ms
TPPreciseTimer (10ms spinlock) 6.0ms 0.002ms 76.5ms
TPPreciseTimer (100ms spinlock) 3.7ms 0.002ms 44.8ms
TPPreciseTimer (200ms spinlock) 2.91ms 0.002ms 74.1ms
dispatch_after (main queue) 14.8ms 0.16ms 161.2ms
dispatch_after (dedicated queue) 19.2ms 0.1ms 174.9ms
dispatch_after (dedicated queue + 100ms spinlock) 22.4ms 0.002ms 306.8ms

So, they appear pretty much the same as the NSRunLoop stats.

Reference : Here

Thanks, Keep Coding:)

iDiscussion : Writing Apps? Juggling Multiple Platforms and the Bumpy Road Ahead

Targeting multiple operating systems has been an industry goal or non-goal depending on your perspective since some of the earliest days of computing. For both app developers and platform builders, the evolution of their work follow typical patterns—patterns where their goals might be aligned or manageable in the short term but become increasingly divergent over time.

While history does not always repeat itself, the ingredients for a repeat of cross-platform woes currently exist in the domain of mobile apps (mobile means apps developed for modern sealed-case platforms such as iOS, Android, Windows RT, Windows Phone, Blackberry, etc.) The network effects of platforms and the “winner take all” state that many believe is reached (or perhaps desirable) influences the behavior and outcome of cross-platform app development as well as platform development.

Today app developers generally write apps targeting several of the mobile platforms. If you look at number of “sockets” over the past couple of years there was an early dominance of iOS followed by a large growth of Android. Several other platforms currently compete for the next round of attention. Based on apps in respective app stores these are two leaders for the new platforms. App developers today seeking the most number of client sockets target at least iOS and Android, often simultaneously. It is too early to pick a winner.

Some would say that the role of the cloud services or the browser make app development less about the “client” socket. The data, however, suggests that customers prefer the interaction approach and integration capability of apps and certainly platform builders touting the size of app stores further evidences that perspective. Even the smallest amount of “dependency” (for customers or technical reasons) on the client’s unique capabilities can provide benefits or dramatically improve the quality of the overall experience.

In discussions with entrepreneurs I have had, it is clear the approach to cross-platform is shifting from “obviously we will do multiple platforms” to thinking about which platform comes first, second, or third and how many to do. Chris Dixon recently had some thoughts about this in the context of modern app development in general (tablets and/or phones). I would agree that tablets drive a different type of app over time simply because the scenarios can be quite different even with identically capable devices under the hood. The cross-platform question only gets more difficult if apps take on unique capabilities or user experiences for different sized screens, which is almost certainly the case.

History

The history of cross-platform development is fairly well-known by app developers.

The goal of an app developer is to acquire as many customers as possible or to have the highest quality engagement with a specific set of customers. In an environment where customers are all using one platform (by platform we mean set of APIs, tools, languages that are used to build an app) the choice for a developer is simple, which is to target the platform APIs in a fully exploitive manner.

The goal of being the “best” app for the platform is a goal shared by both app and platform developers. The reason for this is that nearly any app will have app competitors and one approach to differentiation will be to be the app that is best on the platform—at the very least this will garner the attention of the platform builder and result in amplification of the marketing and outreach of a given app (for example, given n different banking apps, the one that is used in demonstrations or platform evangelism will be the one that touts the platform advantages).

Once developers are faced with two or more platforms to target, the discussion typically starts with attempting to measure the size of the customer base for each platform (hence the debate today about whether market share or revenue define a more successful platform). New apps (at startups or established companies) will start with a dialog that depending on time or resources jumps through incredible hoops to attempt to model the platform dynamics. Questions such as which customers use which platforms, velocity of platform adoption, installed base, likelihood of reaching different customers on platforms, geography of usage, and pretty much every variable imaginable. The goal is to attempt to define the market impact of either support multiple platforms or betting on one platform. Of course none of these can be known. Observer bias is inherent in the process only because this is all about forecasting a dynamic system based on the behavior of people. But basing a product plan on a rapidly evolving and hard to define “market share” metric is fraught with problems.

During this market sizing debate, the development team is also looking at how challenging cross platform support can be. While mostly objective, just as with the market sizing studies, bias can sneak in. For example, if the developers’ skills align with one platform or a platform makes certain architectural assumptions that are viewed favorably then different approaches to platform choices become easy or difficult.

Developers that are fluent in HTML might suggest that things be done in a browser or use a mobile browser solution. Even the business might like this approach because it leverages an existing effort or business model (serving ads for example). Some view the choices Facebook made for their mobile apps as being influenced by these variables.

As the dialog continues, developers will tend to start to see the inherent engineering costs in trying to do a great job across multiple platforms. They will start to think about how hard it is to keep code bases in sync or where features will be easier/harder or appear first or even just sim-shipping across platforms. Very quickly developers will generally start to feel pulled in an impossible direction by having to be across multiple platforms and that it is just not viable to have a long-term cross-platform strategy.

The business view will generally continue to drive a view that the more sockets there are the better. Some apps are inherently going to drive the desire or need for cross-platform support. Anything that is about communications for example will generally argue for “going where the people are” or “our users don’t know the OS of their connected endpoints” and thus push for supporting multiple platforms. Apps that are offered as free front ends for services (online banking, buying tickets, or signing up for yoga class) will also feel pressures to be where the customers are and to be device agnostic. As you keep going through scenarios the business folks will become convinced that the only viable approach is to be on all the popular platforms.

That puts everyone in a very tense situation—everyone is feeling stressed about achieving success. Something has to give though.

We’ve all been there.

Pattern

The industry has seen this cross-platform movie several times. It might not always be the same and each generation brings with it new challenges, new technologies, and potentially different approaches that could lead to different outcomes. Knowing the past is important.

Today’s cross-platform challenge can be viewed differently primarily because of a few factors when looking at the challenge from an app developer / ISV:

  • App Services. Much of the functionality for today’s apps resides on software as a service infrastructure. The apps themselves might be viewed as fairly lightweight front ends to these services, at least for some class of apps or some approaches to app building. This is especially true today as most apps are still fairly “first generation”.
  • Languages and tools. Today’s platforms are more self-contained in that the languages and tools are also part of the platform. In previous generations there were languages that could be used across different platforms (COBOL, C, C++) and standards for those languages even if there were platform-specific language extensions. While there are ample opportunities for shared libraries of “engine” code in many of today’s platforms, most modern platforms are designed around a heavy tilt in favor of one language, and those are different across platforms. Given the first point, it is fair to say that the bulk of the code (at least initially) on the device will be platform specific anyway.
  • Integration. Much of what goes on in apps today is about integration with the platform. Integration has been increasing in each generation of platform shifts. For example, in the earliest days there was no cross-application sharing, then came the basics through files, then came clipboard sharing. Today sharing is implicit in nearly every app in some way.

Even allowing for this new context, there is a cycle at work in how multiple, competing platforms evolve.

This is a cycle so you need to start somewhere.

Initially there is a critical mass around one platform. As far as modern platforms go when iOS was introduced it was (and remains) unique in platform and device attributes so mobile apps had one place to go and all the new activity was on that platform. This is a typical first-mover scenario in a new market.

Over time new platforms emerge (with slightly different characteristics) creating a period of time where cross-platform work is the norm. This period is supported by the fact that platforms are relatively new and are each building out the base infrastructure which tends to look similar across the new platforms.

There are solid technical reasons why cross-platform development seems to work in the early days of platform proliferation. When new platforms begin to emerge they are often taking similar approaches to “reinventing” what it means to be a platform. For example, when GUI interfaces first came about the basics of controls, menus, and windows were close enough that knowledge of one platform readily translated to other platforms. It was technically not too difficult to create mapping layers that allowed the same code to be used to target different platforms.

During this phase of platform evolution the platforms are all relatively immature compared to each other. Each is focused on putting in place the plumbing that approaches platform design in this new shared view. In essence the emerging platforms tend to look more similar that different. The early days of web browsers–which many believed were themselves platforms–followed this pattern. There was a degree of HTML that was readily shared and consistent across platforms. At least this was the case for a while.

During this time there is often a lot of re-learning that takes place. The problems solved in the previous generation of platforms become new again. New solutions to old problems arise, sometimes frustrating developers. But this “new growth” also brings with it a chance to revisit old assumptions and innovate in new ways, even if the problem space is the same.

Even with this early commonality, things can be a real challenge. For example, there is a real desire for applications to look and feel “native”. Sometimes this is about placement of functionality such as where settings are located. It could be about the look or style of graphical elements or the way visual aspects of the platform are reflected in your app. It could also be about highly marketed features and how well your app integrates as evidence for supporting the platform.

Along the way things begin to change and the platforms diverge because of two factors. First, once the plumbing common to multiple early platforms is in place, platform builders begin to express their unique point of view of how platform services experiences should evolve. For example, Android is likely to focus on unique services and how the client interacts with and uses those services. To most, iOS has shown substantially more innovation in client-side innovation and first-party experiences. The resulting APIs exposed to developers start to diverge in capabilities and new API surface areas no longer seem so common between platforms.

Second, competition begins to drive how innovation progresses. While the first mover might have one point of view, the second (or third) mover might take the same idea of a service or API but evolve it slightly differently. It might integrate with backends differently or it might have a very different architecture. The role of voice input/reco, maps, or cloud storage are examples of APIs that are appearing on platforms but the expression of those APIs and capabilities they support are evolving in different ways that there are no obvious mappings between them.

Challenges

As the platforms diverge developers start to make choices about what APIs to support on each platform or even which platforms to target. With these choices come a few well known challenges.

  • Tools and languages.Initially the tools and languages might be different but things seem manageable. In particular, developers look to put as much code in common languages (“platform agnostic code”) or implement code as a web service (independent of the client device). This is a great strategy but does not allow for the reality that a good deal of code (and differentiation) will serve as platform-specific user experience or integration functionality. Early on tools are relatively immature and maybe even rudimentary which makes it easier to build infrastructure around managing a cross-platform project. Over time the tools themselves will become more sophisticated and diverge in capabilities. New IDEs or tools will be required for the platforms in order to be competitive and developers will gravitate to one toolset, resulting in developers themselves less able to context switch between platforms. At the very least, managing two diverging code bases using different tools becomes highly challenging–even if right now some devs think they have a handle on the situation.
  • User interaction and design (assets). Early in platform evolution the basics of human interaction tend to be common and the approaches to digital assets can be fairly straight forward. As device capabilities diverge (DPI, sensors, screen sizes) the ability for the user interaction to be common also diverges. What works on one platform doesn’t seem right on another. Tablet sized screens introduce a whole other level of divergence to this challenge. Alternate input mechanisms can really divide platform elements (voice, vision, sensors, touch metaphors).
  • Platform integration. Integrating with a platform early on is usually fairly “trivial”. Perhaps there are a few places you put preferences or settings, or connect to some platform services such as internationalization or accessibility. As platforms evolve, where and how to integrate poses challenges for app developers. Notifications, settings, printing, storage, and more are all places where finding what is “common” between platforms will become increasingly difficult to impossible. The platform services for identity, payment, and even integration with third party services will become increasingly part of the platform API as well. When those APIs are used other benefits will accrue to developers and/or end-users of apps—and these APIs will be substantially different across platforms.
  • More code in the service. The new platforms definitely emphasize code in services to provide a way to be insulated from platform changes. This is a perfect way to implement as much of your own domain as you can. Keep in mind that the platforms themselves are evolving and growing and so you can expect services provided by the platform to be part of the core app API as well. Storage is a great example of this challenge. You might choose to implement storage on your own to avoid a platform dependency. Such an approach puts you in the storage business though and probably not very competitively from a feature or cost perspective. Using a third party API can pose the same challenge as any cross-platform library. At the same time, the platforms evolve and likely will implement storage APIs and those APIs will be rich and integrate with other services as well.
  • Cross-platform libraries. One of the most common approaches developers attempt (and often provided by third parties as well) is to develop or use a library that abstracts away platform differences or claims to map a unique “meta API” to multiple platforms. These cross—platform libraries are conceptually attractive but practically unworkable over time. Again, early on this can work. Over time the platform divergence is real. There’s nothing you can do to make services that don’t exist on one platform magically appear on another or APIs that are architecturally very different morph into similar architectures. Worse, as an app developer you end up relying on essentially a “shadow” OS provided by a team that has a fraction of the resources for updates, tooling, documentation, etc. even if this team is your own dev team. As a counter example, games commonly use engines across platforms, but they rely on a very narrow set of platform APIs and little integration. Nevertheless, there are those that believe this can be a path (as it is for games). It is important to keep in mind that the platforms are evolving rapidly and the customer desire for well-integrated apps (not just apps that run).
  • Multiple teams. Absent the ability to share app client code (because of differing languages), keeping multiple teams in sync on the same app is extremely challenging. Equally challenging is having one team time slice – not only is that mentally inefficient, maintaining up to date skills and knowledge for multiple platforms is challenging. Even beyond the basics of keeping the feature set the same, there are problems to overcome. One example is just timing of releases. It might be hard enough to keep features in sync and sim ship, but imagine that the demand spike for a new release of your app when the platform changes (and maybe even requires a change to your app). You are then in a position to need a release for one platform. But if you are halfway done with new features for your app you have a very tricky disclosure and/or code management challenge. These challenges are compounded non-linearly as the number of platforms increases.

These are a few potential challenges. Not every app will run into these and some might not even be real challenges for a particularly app domain. By and large, these are the sorts of things that have dogged developers working cross-platform approaches across clients, servers, and more over many generations.

What’s next?

The obvious question will continue to be debated, which is if there is a single platform winner or not. Will developers be able to pick a platform and reach their own business and product goals by focusing on one platform as a way of avoiding the issues associated with supporting multiple platforms?

The only thing we know for sure is that the APIs, tools, and approaches of different platforms will continue to evolve and diverge. Working across platforms will only get more difficult, not easier.

The new platforms moved “up the stack” and make it more difficult for developers to isolate themselves from the platform changes. In the old days, developers could re-implement parts of the platform within the app and use that across platforms or even multiple apps. Developers could hook the system and customize the behavior as they saw fit. The more sealed nature of platforms (which delivers amazing benefits for end-users) makes it harder for developers to create their own experience and transport it across platforms. This isn’t new. In the DOS era, apps implemented their own printing subsystems and character-based user models all of which got replaced by GUI APIs all to the advantage of developers willing to embrace the richer platforms and to the advantage of customers that gained a new level of capabilities across apps.

The role of app stores and approval processes, the instant ability for the community to review apps, and the need to break through in the store will continue to drive the need to be great apps on the chosen platforms.

Some will undoubtedly call for standards or some homogonization of platforms. Posix in the OS world, Motif in the GUI world, or even HTML for browsers have all been attempts at this. It is a reasonable goal given we all want our software investments to be on as many devices as possible (and this desire is nothing new). But is it reasonable to expect vendors to pour billions into R&D to support an intentional strategy of commoditization or support for a committee design? Vendors believe we’re just getting started in delivering inovation and so slowing things down this way seems counter-intuitive at best.

Ultimately, the best apps are going to break through and I think the best apps are going to be the ones that work with the platform not in spite of it and the best apps won’t duplicate code in the platform but work with platform.

It means there some interesting choices ahead for many players in these ecosystems.

BY: Steven Sinofsky

Reference : Here

SolutionPointLogo

iAndroid: Using SQLite on Android Application

iAndroid: Using SQLite on Android Application
Reference Source : Here
With a little care, SQLite can be used as a data store or full database on Android devices
As with most platforms, Android gives us a few options to store data so that it persists even after we’ve terminated the application. Of the various ways we can do this, text files — either stored in the application’s own files directory or to the phone’s SD card — represent one approach. Preferences are also frequently used to store data because they can be both hidden from the user and persist as long as the application is installed. And while not strictly speaking in the same category, Assets can be useful for storing read-only data, too. Assets are essentially files that you bundle into the application package prior to compilation in the project assets folder, which can be accessed at runtime. I will take a closer look at these later.Sometimes, however, we need to be able to carry out complex operations on persistent data, or the volume of data requires a more efficient method of management than a flat text file or preference entry will allow. This is where a mobile database comes in.

Android comes with SQLite (version 3.5.9+), which has been available on the platform since release 1.5 of the OS (the “Cupcake” release). For readers unfamiliar with SQLite, it is a self-contained, server-less, transactional SQL database. While it has its limitations, SQLite serves as a powerful tool in the Android developer’s arsenal.

What I’ll principally cover here is one way to use a SQLite database in Android, concentrating on its management; specifically, creation and update, rather than all the runtime operations.

Managing SQLite

To begin with, we can manage SQLite using a class that extends SQLiteOpenHelper, which comes with a constructor and two required methods; onCreate and onUpgrade.

Naturally, the first of these is executed when the constructor is instantiated; it is here that, via the superclass, we provide four important pieces of data:

  • Context. This is the context of the application. It can be useful to set this in the constructor and store it locally for later use in other methods.
  • Database name. This is the filename (as a String) of the physical database file being accessed.
  • Cursor factory. The cursor factory in use, if any.
  • Database Version. This is the version of your database (as an integer), which I’ll discuss in more detail later. Your initial version should be 1.

For our example, we put these four pieces together and get the following:

1
2
3
4
5
6
7
8
9
10
11
class DB extends SQLiteOpenHelper {
    final static int DB_VERSION = 1;
final static String DB_NAME = "mydb.s3db";
    Context context;
    
    public DB(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        // Store the context for later use
        this.context = context;
    }

The constructor does two things. First, it checks whether the database exists and, if not, will call the onCreate method. Second, if the database does exist, it will check whether the existing database version number differs from the one implemented in the constructor, so as to determine if the database has been updated. If it has, the onUpgrade method will be called.

Additionally, as we now know that the onCreate method is called only when the database does not exist, it can be used as a handy way to determine if you’re dealing with a first run of the application following installation. As such, you can use this method to call any other methods that you need executed only on the first run, such as EULA dialogs.

Let’s look at the database itself. For the purposes of this article, I’m just going to use a very simple employee database with a SQL creation script as follows:

1
2
3
4
5
6
7
CREATE TABLE employees (
 _id INTEGER PRIMARY KEY AUTOINCREMENT,
 name TEXT NOT NULL,
 ext TEXT NOT NULL,
 mob TEXT NOT NULL,
 age INTEGER NOT NULL DEFAULT '0'
);

We can easily construct this by hard-coding and executing the creation SQL, line by line, in our code as follows:

1
2
3
4
5
6
@Override
public void onCreate(SQLiteDatabase database) {
    database.execSQL(
        "CREATE TABLE employees ( _id INTEGER PRIMARY KEY "
    + "AUTOINCREMENT, name TEXT NOT NULL, ext TEXT NOT NULL, "
    + "mob TEXT NOT NULL, age INTEGER NOT NULL DEFAULT '0')");
}

As you can see, this can get quite unwieldy once the database reaches a certain size and complexity, so the ideal solution would be to bundle a SQL creation script as an asset file. To use this approach, you need to write a method that takes in a SQL script from the assets directory and parses it, executing it line by line:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@Override
public void onCreate(SQLiteDatabase database) {
executeSQLScript(database, "create.sql");
}
private void executeSQLScript(SQLiteDatabase database, 
                              String dbname) {
ByteArrayOutputStream outputStream = new  
                              ByteArrayOutputStream();
    byte buf[] = new byte[1024];
    int len;
        AssetManager assetManager = context.getAssets();
    InputStream inputStream = null;
        
    try{
        inputStream = assetManager.open(dbname);
        while ((len = inputStream.read(buf)) != -1) {
            outputStream.write(buf, 0, len);
        }
        outputStream.close();
        inputStream.close();
            
        String[] createScript = 
                   outputStream.toString().split(";");
        for (int i = 0; i < createScript.length; i++) {
                String sqlStatement = createScript[i].trim();
            // TODO You may want to parse out comments here
            if (sqlStatement.length() > 0) {
                    database.execSQL(sqlStatement + ";");
                }
        }
    } catch (IOException e){
        // TODO Handle Script Failed to Load
    } catch (SQLException e) {
        // TODO Handle Script Failed to Execute
    }
}

While this is a more complex approach than simply executing each SQL statement for very simple databases, it quickly pays dividends once the database becomes more complex or you need to pre-populate it. You’ll also see that I abstracted the creation into a separate method called executeSQLScript so that it can be reused in other situations.

Interacting with the Database

Now that the database is created, I want to be able to interact with it. Here’s a brief rundown:

The first step is to open the database and there are two ways to do this: usinggetReadableDatabase() and getWritableDatabase(). The former is faster and uses fewer resources. It should be used for anything that does not require writing or changing the database. The latter call is better suited to INSERTs, UPDATEs, and the like.

In Android, recordsets are returned from queries as Cursor objects. To carry out a query, use either the query() or rawQuery() method. For example, the following two calls return exactly the same data:

1
2
3
4
DB db = new DB(this);
SQLiteDatabase qdb = db.getReadableDatabase();
Cursor recordset1 = 
     qdb.query("mytable", null, null, null, null, null, null);
Cursor recordset2 = qdb.rawQuery("SELECT * FROM mytable", null);

The first call uses a bewildering number of parameters. They are the table name, a string array of the column names, the WHERE clause, the selection arguments, the GROUP BY clause, the HAVING clause, and the ORDER BY clause, respectively. You’ll note that setting many of these as null has the effect of their being treated as wildcards or omitted altogether.

Most of these parameters are fairly straightforward to anyone familiar with SQL. The selection arguments, however, require a little more explanation because they form a string array that interacts with the WHERE parameter, systematically replacing any “?” characters in the clause with a value from the array.

With the rawQuery() approach, there are only two parameters: the first is the SQL query, and the second is the selection argument — akin to those used in the query method. Selection arguments may be preferable to use with complex queries, such as those that use JOINs.

Similarly, INSERTUPDATEDELETE, and a range of other common operations are handled with methods similar to query(); or, as with rawQuery(), they can be executed as raw SQL code using execSQL().

Database Upgrades

Returning to management of the database, let’s look at the tricky scenario of database upgrades. Over time, an app will likely change. New functionality may be added, or it may be better optimized. These changes, in turn, may lead to a requirement to upgrade the database schema and change the value for DB_VERSION in the updated application code to reflect this.

One potential problem is that replacing our database with a new version will end up invalidating the previous version and lead to the loss of data that was present in existing user installations. A second problem is that, once our application has reached a point whereby more than two versions have been released, we cannot presume that the user has been diligently upgrading all along, so a simple upgrade from one version to the next may no longer work.

To deal with this, we already know that if we introduce a new database version, theonUpgrade() method will be called. So ideally, we can use our SQL script parser method and execute one or more update scripts.

Let’s look at what we intend to change in Version 2 of our database in the example:

  • Normalize the phone number data (extension, mobile) into a separate “numbers” table, which includes a numeric field to denote the type of phone number.
  • Add a salary field to the employee table.

Using the Version 1 schema as a starting point, this can be handled by writing a SQL script that updates the schema and then populates it with the data from the older version:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
CREATE TABLE numbers (
   _id INTEGER PRIMARY KEY AUTOINCREMENT,
   employid INTEGER NOT NULL,
   number TEXT NOT NULL,
   ntype INTEGER NOT NULL DEFAULT '0'
);
CREATE INDEX employid ON numbers(employid);
INSERT INTO numbers (employid, number, ntype) SELECT _id, ext, 0
    FROM employees;
INSERT INTO numbers (employid, number, ntype) SELECT _id, mob, 1
    FROM employees;
CREATE TABLE temp (
     _id INTEGER PRIMARY KEY AUTOINCREMENT,
     name TEXT NOT NULL,
     salary INTEGER NOT NULL DEFAULT '0'
);
INSERT INTO temp (_id, name) SELECT _id, name FROM employees;
DROP TABLE employees;
ALTER TABLE temp RENAME TO employees;

Naturally, the more complex the changes in your database schema, the more complex the script you’ll need to write to handle this. SQLite has more limited support for SQL than many databases, so sometimes you’ll need to devise workarounds for these limitations. For example, in the aforementioned update script, I had to employ a temporary table as a workaround for the lack of DROP COLUMN functionality.

Now that I have the SQL upgrade script, I need to handle how it is executed when theonUpgrade method is called. One approach is to do the following:

1
2
3
4
5
6
7
8
9
10
11
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {     
if (newVersion > oldVersion) {
    switch (oldVersion) {
        case 1:
            executeSQLScript(database, "update_v2.sql");
        case 2:
            executeSQLScript(database, "update_v3.sql");
    }
}
}

There are two things to note in this code. The first is that I check to see whether the new database version is greater than the old one. I wrote the code this way because theonUpgrade() method will be called any time these two versions are different, leading to a situation in which version downgrades are also possible. Our code does not envisage this ever occurring, but an else clause and accompanying code could be added to handle this.

The second thing is that there are no break statements between the cases in our switch. This is because each script simply updates from one version to the next, meaning that an upgrade from Version 1 to 3 will first run the upgrade script from Version 1 to 2, then continue on to run the upgrade script from Version 2 to 3. If the database is already at Version 2, it will simply skip the first script and only run the upgrade script from Version 2 to 3.

Thus, each time you upgrade the database, you will only need to replace the create script with one that reflects the new schema (for new installs), and an update script (that handles only an update from the previous version) to handle all possible upgrades. Meanwhile, in our Java code, we need to update the value for DB_VERSION and, naturally, any operations that may be affected by the new database schema.

Conclusion

SQLite can be a very useful means to store and manage data in a persistent manner on Android devices. However, as with any database, care needs to be taken to administer it correctly, particularly with regard to version changes.

Using the script parser solution and saving this part of the application logic as a series of SQL scripts is an efficient and simple management technique to avoid having to write complex methods to the core application to handle each upgrade, thus allowing you to concentrate on the application’s business logic instead.

Thanks 🙂 Keep Coding 🙂

SolutionPointLogo