Common method in Swift

1. Check for any field empty in NSDictionary

class func checkforEmptyValueinDictioanty(dic:NSDictionary)-> Bool{

for (keyVal, dataVal) in dic {

  if (dataVal.length()==0){

                println(\(keyVal): \(dataVal.length()))

                return false




        return true


2.Email validation

class func isValidEmail(testStr:String) -> Bool {

let fullNameArr = testStr.componentsSeparatedByString(“@”)

        var firstPart: String = fullNameArr[0]

        if let range = firstPart.rangeOfCharacterFromSet(NSCharacterSet.letterCharacterSet()){


            return false


      let emailRegEx = “[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}”

 var emailTest = NSPredicate(format:“SELF MATCHES %@”, emailRegEx)

        let result = emailTest.evaluateWithObject(testStr)

        return result


3. Alert in Swift

class func commonAlert(title:String,msg:String,curView:UIViewController){

        var device : UIDevice = UIDevice.currentDevice();

        var systemVersion = device.systemVersion;

        var iosVerion : Float = (systemVersion as NSString).floatValue

        if(iosVerion >= 8.0) {


        var alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.Alert)

            alert.addAction(UIAlertAction(title: “Ok”, style: UIAlertActionStyle.Default, handler: nil))

                  // return alert

            curView.presentViewController(alert, animated: true, completion: nil)


            let alert=UIAlertView(title: title, message: msg, delegate: self, cancelButtonTitle: “ok”)





4. NSUserDefaults in swift as common function

class func saveToUserDefault(value:AnyObject, key:String)


        NSUserDefaults.standardUserDefaults().setObject(value, forKey:key)




    class func userDefaultForKey(key:String) -> String


        return NSUserDefaults.standardUserDefaults().objectForKey(key) as NSString



    class func userDefaultForAny(key:String) -> AnyObject


        return NSUserDefaults.standardUserDefaults().objectForKey(key) as AnyObject!



    class func userdefaultForArray(key:String) -> Array<AnyObject>


        return NSUserDefaults.standardUserDefaults().objectForKey(key) as Array



    class func removeFromUserDefaultForKey(key:String)






5.Get screen height and width

let _screenWidth=UIScreen.mainScreen().bounds.size.width

let _screenHeight=UIScreen.mainScreen().bounds.size.height


Use different font text in a Label in swift

let secondLabel=UILabel(frame: CGRectMake(0, 16, _screenWidth2, 20))



        secondLabel.font=UIFont(name: “Arial”, size: 12)



        let attrSting=NSMutableAttributedString(string: “I agree to the Terms of Service and Privacy Policy.”)


        NSLog(“text length is %d”, attrSting.length)


        attrSting.addAttribute(NSFontAttributeName, value: UIFont(name: “Helvetica-bold”, size: 14), range: NSMakeRange(15, 16))


        attrSting.addAttribute(NSFontAttributeName, value: UIFont(name: “Helvetica”, size: 12), range: NSMakeRange(31,4 ))


        attrSting.addAttribute(NSFontAttributeName, value: UIFont(name: “Helvetica-bold”, size: 14), range: NSMakeRange(35, 15))



Use HexColor in Swift as a color

Add it in your class 

extension UIColor {

   convenience init(red: Int, green: Int, blue: Int) {

       assert(red >= 0 && red <= 255, “Invalid red component”)

       assert(green >= 0 && green <= 255, “Invalid green component”)

       assert(blue >= 0 && blue <= 255, “Invalid blue component”)

       self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)


   convenience init(netHex:Int) {

       self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)



Use it where you need…….

var color = UIColor(red: 0xFF, blue: 0xFF, green: 0xFF)

var color2 = UIColor(netHex:0xFFFFFF)

Open Setting from your iOS application

Step 1.  Add a method in AppDelegate

private func setSettings() {

        let userDefaults = NSUserDefaults.standardUserDefaults()

        let defaults = [ “AppTitle” : “SettingLinker” ]





Step 2. Call this function from didFinishLaunchingWithOptions


Step 3. Add a setting bundle

            Application —> New file —> Resources —> Setting Bundle

******** it will be a pre defined bundle . Change title according to your requirement.

Step 4. Add a Notification to trace changes of setting in Your ViewController’s ViewDidLoad method

override func viewDidLoad() {



        NSNotificationCenter.defaultCenter().addObserver(self,   selector: “traceChanges, name: NSUserDefaultsDidChangeNotification, object: nil)


        // Do any additional setup after loading the view, typically from a nib.


Step 5. Add a method named  traceChanges .

func defaultsChanged() {



Step 6. Add a new Method name  setupView

private func setupView() {

        let userDefaults = NSUserDefaults.standardUserDefaults()

        yourLabelL.text = userDefaults.stringForKey(“AppTitle”)


Step 7. Add a button and addEvent Listener

@IBAction func gotoSetting(sender: AnyObject) {



Best Of luck..

enjoy coding

A soft touch of Apple HealthKit :: HealthKit Tutorial

Screen Shot 2014-10-14 at 6.54.20 PM

HealthKit :: The HealthKit framework provides a structure that apps can use to share health and fitness data. HealthKit is designed to manage data from a wide range of sources, automatically merging the data from all the different sources based on users’ preferences. Apps can also access the raw data for each source and let the app perform its own merging.

Some Key feature related to HealthKit is following

  • To use Healthkit in your application , First you have to enable it . To  enable HeakthKit you have to perform following step .

         Project setting—>Capability pane —> make enable Healthkit

         This requires that you sign in to your Apple developer account, and   

          then acquires the  appropriate entitlements for your app.

  • The HealthKit data is not saved to iCloud or synced across multiple devices. The data is only kept locally on the user’s device. For security, the HealthKit store is encrypted when the device is not unlocked.
  • HealthKit can be used only in iPhone and iPod  , Not in iPad. Developer can check for HealthKit availability using  isHealthDataAvailable().it return a Boolean value that indicates whether HealthKit is available on this device.
  • HKHealthStore is used to managed all types of data in HealthKit.
         if let massNumber = numberString("50") {

      let weightType =   HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)

            let weightValue = HKQuantity(unit: HKUnit(fromString: "kg"), doubleValue: massNumber)

            let metadata = [ HKMetadataKeyWasUserEntered : true ]

            let now = NSDate()

            let sample=HKQuantitySample(type: weightType, quantity: weightValue, startDate: now, endDate: now, metadata: metadata)
  • All access to the data is performed through a HKHealthStore object, and it is this that you request permissions from. access request of data from Store is done as following
private func requestAuthorisationForHealthStore() {

  let dataTypesToWrite = [



  let dataTypesToRead = [






  self.healthStore?.requestAuthorizationToShareTypes(NSSet(array: dataTypesToWrite),

    readTypes: NSSet(array: dataTypesToRead), completion: {

    (success, error) in

      if success {

        println("User completed authorisation request.")

      } else {

        println("The user cancelled the authorisation request. \(error)")



  • Samples are saved in store using HKHealthStore object . sample code for this is following


        func saveSampleToHealthStore(sample: HKObject) {

  println(“Saving weight”)

  self.healthStore?.saveObject(sample, withCompletion: {

    (success, error) in

    if success {

      println(“Weight saved successfully “)

    } else {

      println(“Error: \(error))




  • Data from Store can be retrieved from HKQuery . sample code to retrieve is following


          func perfromQueryForWeightSamples() {

  let endDate = NSDate()

  let startDate = NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitMonth,

    value: –2, toDate: endDate, options: nil)

  let weightSampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)

  let predicate = HKQuery.predicateForSamplesWithStartDate(startDate,

    endDate: endDate, options: .None)

  let query = HKSampleQuery(sampleType: weightSampleType, predicate: predicate,

    limit: 0, sortDescriptors: nil, resultsHandler: {

    (query, results, error) in

      if !results {

        println(“There was an error running the query: \(error))


      var data=results as [HKQuantitySample]




HealthKit Support 50 type of exercise including

     • Archery

  • Yoga
  • Swimming
  • StairClimbing
  • SnowSports
  • SkatingSports
  • Hocket
  • Fishing
  • Dance
  • CrossTraining

Type of values that can be stored in store is following

  •          1. Body Mass
  •          2. Height
  •          3.Step Count
  •          4.Blood glucose
  •          5.Blood alcohol content
  •          6.Dietary energy consumed
  •          7.Body Temperature
  •          8.Inhaler usage

         these are known as HKTypeIdentifiers.

For detail check on

Continue reading

Basic HTTP Authentication in iOS while calling webservice

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

    if ([challenge previousFailureCount] == 0) {

        NSLog(@”received authentication challenge”);

        NSURLCredential *newCredential = [NSURLCredentialcredentialWithUser:@”tylerhorne”



        NSLog(@”credential created”);

        [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];

        NSLog(@”responded to authentication challenge”);


    else {

        NSLog(@”previous authentication failure”);



Post Json data to server in iOS


NSString *url= SERVER_URL;

NSLog(@”url is %@”,url);


NSMutableURLRequest *_request = [NSMutableURLRequestrequestWithURL:[NSURLURLWithString:url]




NSMutableDictionary *post=[[NSMutableDictionaryalloc] init];

[post setObject:_emailText.text forKey:@”username”];

[post setObject:_passText.text forKey:@”password”];


NSError *error;

NSData *data=[NSJSONSerializationdataWithJSONObject: post options:kNilOptionserror:&error];

NSString *jsonString = [[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding];

NSString *post = [NSString stringWithFormat:@”json=%@”, jsonString];

NSData*postData = [post dataUsingEncoding:NSASCIIStringEncodingallowLossyConversion:NO];


NSLog(@”string is %@”,post);

[_request setHTTPMethod:@”POST”];

[_request setValue:@”application/x-www-form-urlencoded”forHTTPHeaderField:@”content-type”];

[_request setHTTPBody:postData];


NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:_request delegate:self];

[connection start];





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

if ([challenge previousFailureCount] == 0) {

NSLog(@”received authentication challenge”);

NSURLCredential *newCredential = [NSURLCredentialcredentialWithUser:@”tylerhorne”



NSLog(@”credential created”);

[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];

NSLog(@”responded to authentication challenge”);


else {

NSLog(@”previous authentication failure”);





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





– (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data


// Append the new data to receivedData.

// receivedData is an instance variable declared elsewhere.


NSDictionary *response=[NSJSONSerializationJSONObjectWithData:data options:kNilOptionserror:nil];

NSLog(@”response %@”,response);






– (void)connection:(NSURLConnection *)connection

didFailWithError:(NSError *)error



NSLog(@”Connection failed! Error – %@ %@”,

[error localizedDescription],

[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);


Live Video Face Masking on iOS

A great post to live video processing

Chris Cavanagh's Blog

Face detection has been possible for some time on iOS thanks to libraries like OpenCV. The CIDetector class introduced in iOS 5 made it a standard feature. Since iOS 7 it can also detect smiles and eye blinks Smile

With iOS 6, AV Foundation gained AVCaptureMetadataOutput, allowing face detection to be included in the capture pipeline (in iOS 7 it also supports barcode scanning).

Here’s how you could use that to perform face masking on live video:


First thing to do is get the capture session set up:

 AVCaptureSession *captureSession = [AVCaptureSession new]; [captureSession beginConfiguration]; NSError *error; // Input device AVCaptureDevice *captureDevice = [self frontOrDefaultCamera]; AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error]; if ( [captureSession canAddInput:deviceInput] ) { [captureSession addInput:deviceInput]; } if ( [captureSession canSetSessionPreset:AVCaptureSessionPresetHigh] ) { captureSession.sessionPreset = AVCaptureSessionPresetHigh; } // Video data output AVCaptureVideoDataOutput *videoDataOutput = [self createVideoDataOutput]; if ( [captureSession canAddOutput:videoDataOutput] ) { [captureSession addOutput:videoDataOutput]; AVCaptureConnection *connection…

View original post 511 more words

Make a Very fast Android emolator

Testing on multiple mobile devices is costly, time consuming and the default Android emulator is notoriously slow. So, what should we do? That’s easy – start using a properly fast Android emulator.
When developing Android applications, you have to keep in mind all the different Android OS versions and various screen sizes and resolutions. The main objective before releasing an application is to find bugs and design imperfections.

Default Android emulator
The great thing about using an emulator for development is that it gives you an opportunity to develop applications without having a real Android device. The default Android emulator comes together with the Android SDK and can be found in the “tools” folder.

So far so good, we have our cake, but can we eat it? The answer comes about 5 minutes after we hit the “Launch” button. Go grab a coffee. Have breakfast. Come back. Wait another 5 minutes. Maybe even more.

Finally – the emulator launches, only to show how slow it actually is.

Boot animation

All these performance problems stem from the fact that it emulates an ARM processor so it can run the actual code of your application. It accomplishes that by providing dynamic binary translation of the device machine code to the OS and processor architecture of your development machine.

Basically, it does a lot of mumbo-jumbo to pretend it’s an ARM processor – when actually it isn’t.


Well, first, we can help our CPU out by delegating the rendering process to the GPU by checking “Use Host GPU” checkbox in AVD’s edit window. The screen should now look better and be more responsive. That’s because the CPU is not dealing with the tedious work of doing rendering anymore. But, that’s still not fast enough.
Host GPU

We can download Intel Atom (x86) images and, while we’re at it, download Intel x86 Emulator Accelerator (HAXM, for Mac and Windows only). This will enable virtual machine acceleration capabilities of the Intel CPU (for more information check this link).
Now we’re getting somewhere, once this baby starts up, it should run fast and smooth.

x86 and HAXM

You could say that this level of speed should be sufficient. That may be true, but an issue with the Intel x86 images is that you don’t get Google Apps, they only come with ARM images. This is important if you’re testing an app that uses GMaps, or Google Play Services.

So, as we’ve seen, ARM images aren’t fast enough even with hardware acceleration. And emulators don’t have the Play Store. What now?

Genymotion by Genymobile
Genymotion is a new, fast Android emulator developed by the French company Genymobile. It’s based on the open-source project AndroVM, and the first beta version was released back in June.

It runs on all major platforms (Mac, Windows, Linux). For now it’s freely available, but there is also going to be a paid version.

According to AndroVM blog, the free version will be feature-rich, and the paid version will be intended for large companies needing a higher level of collaboration on Genymotion.


Genymotion relies on Oracle VirtualBox to work (version 4.1 or above). So…

Download and install VirtualBox. For Windows users it’s not necessary to install VirtualBox separately, because it is available from the Genymotion site, bundled with the Genymotion emulator.

Go to Genymotion website and sign up. You’ll receive a validation mail, so just click on the validation link to proceed.

Download and install the Genymotion emulator (the current version is 1.1.0).

Start Genymotion. You might need to configure path to your Android SDK location in Genymotion settings (probably if you’ve installed SDK in a non default location). Since this is a first start, there are no devices. Click on “Add” and download new device. To see available devices, write your credentials in the pop-up dialog and click “Connect”.

Select the device and click “Start”.

It starts quickly and is insanely fast! It’s a little awkward to start the emulator separately, but Genymotion provides Eclipse and Android Studio integration through plugins, also available on Genymotion website. To use the plugin, you have to provide a path to Genymotion installation and Android SDK, as well.

Eclipse plugin


Well, for me, the sheer speed of Genymotion is what got me using it in the first place. Which is kind of funny, because in the first version you couldn’t even rotate the device.

But, alongside the speed bump, it also provides GPS, compass and battery control via some good-looking widgets.


Battery control widget


The GPS widget even provides GMaps for selecting mock locations, which is really nice for testing location based apps.


Through the Genymotion shell it’s also possible to control the device’s angle (accelerometer), but it would be cool to control it using a widget, something like the Windows phone emulator does.


Genymotion devices with Google Apps also come with the Play Store preinstalled. This comes in handy if you want to test an app from the Play Store quickly.


Multiple screen sizes are one of Android developer’s worst nightmares. There is a huge number of different screen configurations of Android devices.

Android multiple screen sizes

Genymotion, as well as the default emulator, offers custom configuration of device’s screen. In the list of available devices, select the device for which you want to change screen configuration and click on the monitor icon on the right side. Then simply select one of the predefined screen resolutions or create your own.

Screen configuration

Final result

Be careful when choosing resolution, because you may end up with something rather strange…


The main setback of Genymotion is that it only provides devices with API version 16, 17 and a preview version of Android 4.3 (API 18). If we take a look at Google Dashboard, we’ll see that Gingerbread still holds about 33% of all devices (API 10).

So, for testing on that platform you still need either a default emulator or real device, which kind of defeats the purpose of Genymotion as a testing platform.

And there is no camera, which I don’t miss, but could be really useful.

In the future, we can expect even more features, like taking screenshots or video screen capturing (which would be great for making demonstration videos). An accelerometer widget would be cool, and even a camera would be nice, but we can only wait and see.

Final thoughts
Well, you can never really get rid of real devices, because you’ll always want to test an app on a real device before releasing it. But during development I recommend using a Genymotion emulator. Even though it doesn’t cover all major Android OS versions. It’s fast, stable, the GPS sensor manipulation is awesome and with the device rotation feature added to the 1.1.0 version – it’s truly the way to go.

Also, deploying apps is almost instant and that can save you a lot of time when you’re doing small changes to the app. But you have to watch out since the Genymotion emulator runs faster than real devices themselves, giving you a false impression of the performance of the app.

Always test on a real device!

Develop first Android Game with AndEngine

There are many frameworks you can use to make games on Android – the most popular being libGDX, AndEngine and Cocos2D-X. Each engine has its pros and cons.
Cocos2D-X (which we previously covered in a two-part series here and here) is great for making cross-platform games, but it does bring along a bit of extra complexity.
What if you just want to get a simple game working on Android the quickest and easiest way? This is where AndEngine comes in handy! Its API is very easy to use and it takes hardly any time to learn the ins and outs of the engine.
You’ll put AndEngine to work creating a version of the famous mathematical puzzle the Tower of Hanoi. Before you begin, make sure you’ve read my previous two tutorials on Getting Started with Android (here and here), or have some Android development experience under your belt.
Keep reading to get started with AndEngine!
All About the AndEngines
AndEngine logo
Which do you like better, this or the Cocos2D logo?
First, here’s a brief overview of AndEngine, including what I like and dislike about it.
AndEngine is currently available in two flavors: GLES1 and GLES2. As you might have gathered from the name, the GLES1 version supports OpenGL ES 1.x. Almost 99% of Android devices can run a game built using this version.
GLES2, as you might guess, supports OpenGL ES 2.0. This branch is actively being worked on, and nearly 93% of current Android devices can run a game that’s been made with this branch.
AndEngine Pros:
It has a complete 2-D scene graph, with a very easy-to-use API.
It works really well with the Android activity lifecycle.
It has a number of extensions that can be added as plugins.
It’s free :]
AndEngine Cons:
The biggest problem I’ve faced while using AndEngine is that the API is undocumented. This can increase the development time, as you sometimes need to go through the engine source code to figure things out. Don’t worry though – I’ve got you covered in this tutorial! :]
Getting Started
Now that you know a bit more about AndEngine, it’s time to download the source code and set up the environment.
Note: Since AndEngine is hosted on GitHub, you could always clone the git repository for AndEngine to get the source code for the project. However, this requires that you have git installed on your machine and that you are able to work on the command line.
Open up your browser and go to the AndEngine github page. You should see a link on the page to download the repository as a ZIP file. Use that to download a copy of the AndEngine project. Or, you should be able to use this link to download the file directly.
Extract the downloaded ZIP file to a convenient location on your hard drive.
Now that you’ve got the source code for the game engine, if you want, you can also download the code for additional AndEngine extensions. In this tutorial, you will not be using any of the extensions but you will need all of them in place if you wanted to try out the AndEngine sample project, which is also available on GitHub.
The sample project is a great way to learn the different ways to use AndEngine and you can always get the latest sample project and the extensions by downloading each of them from GitHub, setting up the projects, and building the sample. However, that is probably beyond the scope of this tutorial and so we’ll leave that to you to figure out, if you’re interested :] You can find it all at
Setting Up the Environment
Before you start coding, there are a few things you should know about AndEngine:
OpenGL ES 2.0: The currently developed version of AndEngine is the GLES 2.0 version. This version requires OpenGL ES 2.0 support in order to function. So you need to make sure that your device (or emulator) supports OpenGL ES 2.0. If you are using the emulator to test, then you need graphics acceleration support and this is there only in the latest SDK Tools version. As of this tutorial, the latest SDK Tools version available is revision 19. Make sure that you have at least this version installed. To upgrade, please follow the instructions given here.
Android 4.0.3: You also need Android SDK Platform API 15, Revision 3 or higher in order to test OpenGL ES 2.0 based code on the emulator. So make sure that you’ve upgraded to at least Android 4.0.3, which is API 15. You emulator used for testing AndEngine code should be using Android 4.0.3.
Emulator: If you are using the emulator to test AndEngine code, you need a virtual device which has GPU emulation enabled and is running at least Android 4.0.3. So check your virtual device configuration and edit it if your device is not set up appropriately.
With that done, it’s time to start Eclipse, the IDE usually used for Android development. So go ahead an start Eclipse.
The version of AndEngine that you downloaded from GitHub already contains an Eclipse project file. You can simply import that by going to File->Import … That should open the following dialog:
Select “Existing Projects into Workspace” from the dialog and click “Next”. A new dialog should open where you must specify the location of the AndEngine project. It looks something like this:
Click the “Browse” button and browse to the folder where you extracted the AndEngine source ZIP file. The existing project should be detected and show up automatically in the dialog. Click “Finish”. And you should have the project imported into your Eclipse workspace – it’s that simple :]
If by some chance the extracted source is missing the Eclipse project information, you can create a new project by going to File->New->Project. A window like the one shown in the image below will open. Select Android Project and click Next.

Give the project a name: I suggest sticking with “AndEngine.” Select the “Create project from existing source” option. Next click the browse button, go to the location of the AndEngine source code and select Open. Once you’ve found the right location, press Finish. This will create a new project called AndEngine that you can view in the project navigator.

Your AndEngine project is now ready. This way, you can add your AndEngine project as a library to your tutorial project and the AndEngine library will be compiled in as part of your tutorial project.
The Tower of Hanoi
Time to start making your first Android game!! The game for this tutorial will be a simple version of the Tower of Hanoi puzzle. The finished project will look like this:

The objective of the Tower of Hanoi is to move all the rings over to the third rod, while only moving one ring at a time and without placing a larger ring on top of a smaller one.
Start by creating a new project. Open Eclipse and go to File->New and select Project, then select Android Project. Fill out all the details. I used the project name “TowerOfHanoi” and the package name “com.tutorial.towerofhanoi.” Feel free to use any name you wish, though it will be easier to stay in sync with the tutorial if you follow the same naming conventions.
Next add AndEngine as a library to your project. Right-click on the project and select Properties. Select Android in the left panel of the pop-up window. You should see a window like the one below:

From here you can add the engine as a library to the project. Click the Add button to add the AndEngine project. Once this is done, click Apply and then Okay.
Start Your AndEngine
Now you can begin coding. Open the src directory for the project via the Eclipse project navigator. If you drill down, (and if you used the suggested names) you should find a Java file called “”. (If you opted to name the first activity created something else, then find that file.) Open this file.
In Android development, an Activity is a single focused thing which interacts with the user. For instance, when you start an app, you can have a login activity which allows the user to login using their authentication credentials. And if the user doesn’t have a login, you might provide a second registration activity which will allow them to create a login.
The first file created by the project is also an Activity. And the first thing to do in our project is to change the class that this Activity extends. Instead of extending the Activity class, you want to make it extend a class called SimpleBaseGameActivity. And it’s fairly simple to do that, but in order to refer to the SimpleBaseGameActivity class, we need to add a few import statements for it. So we add that first to the top of the file under the existing import line:
import org.andengine.ui.activity.SimpleBaseGameActivity;
import org.andengine.engine.options.EngineOptions;
import org.andengine.entity.scene.Scene;
Note: Technically, you don’t have to always add the import statements first. You can always add your code in, look for the red underlines beneath classes, let the Eclipse code-fix tell you what import is needed and let it add the imports for you. But this might get a little bit confusing when you’re not sure which import to add when you get a several different choices. So in this tutorial, we’ll always add the imports first.
Now, just change the class definition line, similar to the following:
public class TowerOfHanoiActivity extends Activity {
To something like this:
public class TowerOfHanoiActivity extends SimpleBaseGameActivity {
The SimpleBaseActivity class provides additional callbacks and contains the code to make AndEngine work with the Activity life cycle. Each callback that it provides is used for a specific purpose. As soon as you extend this class, you’ll have to override three functions. Here is a brief description of each of those functions:
onCreateEngineOptions: This function is where you create an instance of the engine. Every activity that the game uses will have its own instance of the engine that will run within the activity lifecycle.
onCreateResources: This is the function where you’ll load all the resources that the activity requires into the the VRAM.
onCreateScene: This function is called after the above two callbacks are executed. This is where you create the scene for your game and use all the textures that you previously loaded into memory.
We will first add some empty placeholders for the above callbacks so that we have some skeleton code. Replace the existing contents of our TowerOfHanoiActivity class with the following (if you started with an automatically created Activity, you should have an onCreate method implementation):
public EngineOptions onCreateEngineOptions() {
// TODO Auto-generated method stub
return null;

protected void onCreateResources() {
// TODO Auto-generated method stub

protected Scene onCreateScene() {
// TODO Auto-generated method stub
return null;
Next, create a few static variables. These will be private to our class. So add the following code right below the class definition line:
private static int CAMERA_WIDTH = 800;
private static int CAMERA_HEIGHT = 480;
These two static variables define the width and height of the camera that the engine will use. This means that the final dimensions of the game scene will be equal to the camera size and width.
Next, you’re going to write code to initialize an instance of the engine. But that code is going to require several import statements in order to function properly. So first add the following imports to the top of the file below the existing import statements:
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
Now, add the following code for the onCreateEngineOptions function, replacing the placeholder conent which is in there at the moment:
final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED,
new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera);
In the above code, you create a new instance of the Camera class. Then we use that camera object to create the EngineOptions object that defines the options with which the engine will be initialized. The parameters that are passed while creating an instance of EngineOptions are:
FullScreen: A boolean variable signifying whether or not the engine instance will use a fullscreen.
ScreenOrientation: Specifies the orientation used while the game is running.
ResolutionPolicy: Defines how the engine will scale the game assets on phones with different screen sizes.
Camera: Defines the width and height of the final game scene.
Take a step back for a moment. As you know, Android runs on a lot of devices with different screen sizes. Keeping this in mind, it becomes very difficult to resize the game scene for each device. AndEngine comes with a unique solution to this problem: it will automatically scale the game assets to fit the screen size of the device.
If you set your CAMERA_WIDTH/CAMERA_HEIGHT to 480×320 and someone runs it on a phone with a 800×480 screen size, your game will be scaled up to 720×480 (1.5x) with a 80px margin (top, bottom, left, or right). Notice that AndEngine keeps the same aspect ratio and scales the game scene to the closest possible value to the actual screen size.
Loading Game Assets to VRAM
Now that you’ve initialized an instance of the engine, you can load all the assets required by the Tower of Hanoi game into memory. First download the game assets here.
Next create a new folder within the assets folder already present in your project. To do this, right-click on the assets folder and select New->Folder, name the folder “gfx” and copy all the downloaded assets to that folder.
To load these assets, we’re going to add the onCreateResources method. But as you might guess, our new code references several other classes for which we need to add imports. So add the following at the top of the file below the rest of the import statements:
import org.andengine.opengl.texture.ITexture;
import org.andengine.opengl.texture.bitmap.BitmapTexture;
import org.andengine.util.debug.Debug;

Now, replace the placeholder content in onCreateResources with the following:
try {
// 1 – Set up bitmap textures
ITexture backgroundTexture = new BitmapTexture(this.getTextureManager(), new IInputStreamOpener() {
public InputStream open() throws IOException {
return getAssets().open(“gfx/background.png”);
ITexture towerTexture = new BitmapTexture(this.getTextureManager(), new IInputStreamOpener() {
public InputStream open() throws IOException {
return getAssets().open(“gfx/tower.png”);
ITexture ring1 = new BitmapTexture(this.getTextureManager(), new IInputStreamOpener() {
public InputStream open() throws IOException {
return getAssets().open(“gfx/ring1.png”);
ITexture ring2 = new BitmapTexture(this.getTextureManager(), new IInputStreamOpener() {
public InputStream open() throws IOException {
return getAssets().open(“gfx/ring2.png”);
ITexture ring3 = new BitmapTexture(this.getTextureManager(), new IInputStreamOpener() {
public InputStream open() throws IOException {
return getAssets().open(“gfx/ring3.png”);
// 2 – Load bitmap textures into VRAM
} catch (IOException e) {
In the above code, you first create an ITexture object. ITexture is an interface. An object of this type is initialized to a BitmapTexture object, which, you guessed it, is used to to load a bitmap into VRAM. The above code creates ITexture objects for all the assets you downloaded, and loads them into VRAM by calling the load method on each object.
Now that you have all your assets loaded, you need to extract TextureRegions from your textures. Think of a texture as a giant canvas that has to have width and height values which are a power of 2 (a requirement of OpenGL ES). A TextureRegion, on the other hand, is a part or a region of a texture that does not have to have dimensions which are a power of 2.
Note: Instead of creating textures for each of your assets, you could have loaded all the assets into one texture and extracted the individual assets as TextureRegions. Doing this is out of scope for this tutorial, but I may cover it in detail in a future tutorial.
As you might guess, we have to add a few new import statements first:
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.TextureRegionFactory;
Now, to hold the TextureRegions, add private variables to our class (again, at the top of the file, below the previous private variables):
private ITextureRegion mBackgroundTextureRegion, mTowerTextureRegion, mRing1, mRing2, mRing3;
Finally, add these lines of code to onCreateResources, right after the end of section #2 where you load the bitmap textures into VRAM:
// 3 – Set up texture regions
this.mBackgroundTextureRegion = TextureRegionFactory.extractFromTexture(backgroundTexture);
this.mTowerTextureRegion = TextureRegionFactory.extractFromTexture(towerTexture);
this.mRing1 = TextureRegionFactory.extractFromTexture(ring1);
this.mRing2 = TextureRegionFactory.extractFromTexture(ring2);
this.mRing3 = TextureRegionFactory.extractFromTexture(ring3);
The above code initializes your TextureRegions using the textures that you already loaded into VRAM.
Creating the Game Scene
It’s finally time to create the game scene! Of course, we need another new import:
import org.andengine.entity.sprite.Sprite;
Next, replace the placeholder content in onCreateScene with the following:
// 1 – Create new scene
final Scene scene = new Scene();
Sprite backgroundSprite = new Sprite(0, 0, this.mBackgroundTextureRegion, getVertexBufferObjectManager());
return scene;
The above code first creates a Scene object. Next you create a sprite called backgroundSprite and attach the sprite to the scene. Notice that this method requires you to return the scene object. Think of a scene as a container with a number of layers, and each layer can have many sprites (TextureRegions) placed within it.
When creating a Sprite object, you pass four parameters. Here’s a brief description of each parameter:
xCoordinate: Defines the X-position of the sprite. The AndEngine coordinate system considers the top-left point as the origin.
yCoordinate: Defines the Y-position of the sprite.
TextureRegion: Defines what part of the texture the sprite will use to draw itself.
VertexBufferObjectManager: Think of a vertex buffer as an array holding the coordinates of a texture. These coordinates are passed to the OpenGL ES pipeline and ultimately define what will be drawn. A VertexBufferObjectManager holds all the vertices of all the textures that need to be drawn on the scene.
Compile and run the application. You should see something like this:

Nice, we’re starting to see something! However, this platform does look a little bit desert-ed (groan) ;]
The Three Towers
It’s time to add the sprites for the towers and rings – the final step before getting things moving with the game logic. Start by adding three private variables to the class. Declare the variables as follows:
private Sprite mTower1, mTower2, mTower3;
Next add the following lines of code to onCreateScene, right before the final return statement:
// 2 – Add the towers
mTower1 = new Sprite(192, 63, this.mTowerTextureRegion, getVertexBufferObjectManager());
mTower2 = new Sprite(400, 63, this.mTowerTextureRegion, getVertexBufferObjectManager());
mTower3 = new Sprite(604, 63, this.mTowerTextureRegion, getVertexBufferObjectManager());
You’ve defined three sprites, each using the TextureRegion of the tower that you loaded in onCreateResources.Then you added these sprites to your scene. That’s all there is to it!
Compile and run. You should now see the three towers placed in their proper positions.

And One Ring to Bind Them
Let’s talk a little about the game logic before you create your rings. Think of the towers as three stacks (I mean the data structure) – you can only remove the top-most element, and when you add an element it will always be on top. You’ll use these stacks when you write the game logic code.
To create the rings, we need to first make a custom class that will extend Sprite. You do this because every ring needs to know which stack it belongs to.
Right-click on the folder containing and select New->Class. You should see a dialog which you should fill in similar to the following:
Note that you probably would have “Source folder” and “Package” filled in automatically. All you’d need to do is type in the “Name” and click “Browse…” next to “Superclass” to find the Sprite class from AndEngine. That should create a Java file called “” Place the following code within the class implementation (after the public class line and before the closing curly brace):
private int mWeight;
private Stack mStack; //this represents the stack that this ring belongs to
private Sprite mTower;

public Ring(int weight, float pX, float pY, ITextureRegion pTextureRegion, VertexBufferObjectManager pVertexBufferObjectManager) {
super(pX, pY, pTextureRegion, pVertexBufferObjectManager);
this.mWeight = weight;

public int getmWeight() {
return mWeight;

public Stack getmStack() {
return mStack;

public void setmStack(Stack mStack) {
this.mStack = mStack;

public Sprite getmTower() {
return mTower;

public void setmTower(Sprite mTower) {
this.mTower = mTower;
Most of the code here is pretty straightforward. The object has three private variables. One is used to keep track of the weight of the tower; this is an integer value, i.e., the higher the value, the bigger the ring. The other two variables are used to store the stack that the ring belongs to and the tower on which it is currently placed.
You’ll also need to add the following import statements to the top of the file:
import java.util.Stack;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
Now that we have the Ring class, to create and add the rings, add the following lines of code to onCreateScene, right before the return statement:
// 3 – Create the rings
Ring ring1 = new Ring(1, 139, 174, this.mRing1, getVertexBufferObjectManager());
Ring ring2 = new Ring(2, 118, 212, this.mRing2, getVertexBufferObjectManager());
Ring ring3 = new Ring(3, 97, 255, this.mRing3, getVertexBufferObjectManager());
Compile and run to test.
You’ll notice that the rings are now on the first tower but you can’t move the rings. That’s because we haven’t worked out the game logic for placing and moving the rings. So that’s what you’ll do next :]
Game Logic
Ready to bring your Tower of Hanoi puzzle to life? As mentioned before, as the foundation of the game logic, you’re going to create three stacks, each representing a tower. Start by adding the following import for the Stack class to
import java.util.Stack;
Next, declare the stack variables below the other private variables:
private Stack mStack1, mStack2, mStack3;
You’ll initialize these variables in onCreateResources. Add the following lines of code after the end of section #3:
// 4 – Create the stacks
this.mStack1 = new Stack();
this.mStack2 = new Stack();
this.mStack3 = new Stack();
When the game starts, all three rings should be in the first stack. Put the following code in onCreateScene right before the return statement:
// 4 – Add all rings to stack one
// 5 – Initialize starting position for each ring
// 6 – Add touch handlers
In the above code, you do the following:
Added the rings to the first stack.
Set the stack variable of each ring as the first stack and the tower variable as the first tower.
To handle touch and movement of the rings, you registered each ring as a touchable area.
Enabled touch binding.
Now, you need to override the onAreaTouch method of the Sprite class. This is where you’ll add logic to move the rings. But that code in turn will require a method which checks whether a ring collided with a tower. You’ll write that code later, but you need to add an empty method place holder for collision detection as follows (you can add this to the end of the class):
private void checkForCollisionsWithTowers(Ring ring) {
You also need to add the following import in order for the ring movement code to be able to identify the relevant classes:
import org.andengine.input.touch.TouchEvent;
Now, replace the first three lines of section #3 in onCreateScene (where you defined the rings) with the following:
Ring ring1 = new Ring(1, 139, 174, this.mRing1, getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) {
if (((Ring) this.getmStack().peek()).getmWeight() != this.getmWeight())
return false;
this.setPosition(pSceneTouchEvent.getX() – this.getWidth() / 2,
pSceneTouchEvent.getY() – this.getHeight() / 2);
if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_UP) {
return true;
Ring ring2 = new Ring(2, 118, 212, this.mRing2, getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) {
if (((Ring) this.getmStack().peek()).getmWeight() != this.getmWeight())
return false;
this.setPosition(pSceneTouchEvent.getX() – this.getWidth() / 2,
pSceneTouchEvent.getY() – this.getHeight() / 2);
if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_UP) {
return true;
Ring ring3 = new Ring(3, 97, 255, this.mRing3, getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) {
if (((Ring) this.getmStack().peek()).getmWeight() != this.getmWeight())
return false;
this.setPosition(pSceneTouchEvent.getX() – this.getWidth() / 2,
pSceneTouchEvent.getY() – this.getHeight() / 2);
if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_UP) {
return true;
Notice that onAreaTouched returns a boolean value. When it returns true, the touch is consumed, otherwise it is passed down to other layers until someone consumes it. So the first thing you do in this method is check if the weight of the current ring is not equal to the weight of the first ring in the stack. If it is, that means this ring is the first element of the stack and so you can proceed to move it, otherwise you let the touch go since you can’t move this ring.
You also check in onAreaTouched if the type of touch is an ACTION_UP event, triggered when the finger is lifted. If it is, you call checkForCollisionsWithTowers whose primary purpose is to check if the ring has collided with (or rather, is touching) a tower. As you may recall, you added a placeholder for checkForCollisionsWithTowers already. Let’s fill the function in now.
Replace the placeholder method for checkForCollisionsWithTowers with the following:
private void checkForCollisionsWithTowers(Ring ring) {
Stack stack = null;
Sprite tower = null;
if (ring.collidesWith(mTower1) && (mStack1.size() == 0 ||
ring.getmWeight() < ((Ring) mStack1.peek()).getmWeight())) {
stack = mStack1;
tower = mTower1;
} else if (ring.collidesWith(mTower2) && (mStack2.size() == 0 ||
ring.getmWeight() < ((Ring) mStack2.peek()).getmWeight())) {
stack = mStack2;
tower = mTower2;
} else if (ring.collidesWith(mTower3) && (mStack3.size() == 0 ||
ring.getmWeight() 0) {
ring.setPosition(tower.getX() + tower.getWidth()/2 –
ring.getWidth()/2, ((Ring) stack.peek()).getY() –
The above code checks whether the given ring is touching a tower, if it is, whether it can be moved to that tower, and if yes, places the ring appropriately.
Build and run, and you should have a completely functional Tower of Hanoi game! There are only three rings, but that means you should be able to beat the game in no time. 😛
Where to Go From Here?
Here is the complete source code of the project.
There are a number of things left to be done, but these are easy enough to accomplish. So I’m going to leave them as an exercise for you :] Possible additions include:
Detecting when all the rings have been moved to the third tower and showing a Game Over pop-up.
Counting and displaying the total number of moves.
Calculating and displaying the minimum number of moves required. (Hint: with three rings, the puzzle can be solved in seven moves.)
Allowing the user to increase the difficulty by adding more rings. Legend has it that there is a temple where the priests are working on a version of this puzzle with 64 rings! I don’t suggest you create a version of this game with that many rings, unless you want to spend 580 billion years solving it!
Try your hand at these improvements and let me know how you fare in the forums!