Showing posts with label iphone sdk. Show all posts
Showing posts with label iphone sdk. Show all posts

Saturday, October 10, 2015

Custom UISwitch in iOS

I wanted to create Custom UISwitch in my iOS game. Initially I just waned to change size, font and color and for that I used UICustomSwitch from Hardy Macia found at here. It's quite easy to use and customisable, but then I wanted to switch to use custom image instead of standard one. For that I need to modify code a bit, below is the code which use custom image to create UISwitch. BTW this is how it looks


Header is same as original implementation, but I removed unnecessary properties and added left and right images required to display on and off images for switch.
@interface UICustomSwitch : UISlider {
    BOOL on;
    UIImageView* leftImage;
    UIImageView* rightImage;
 
    BOOL touchedSelf;
}

@property(nonatomic,getter=isOn) BOOL on;
@property (nonatomic, retain) UIImageView* leftImage;
@property (nonatomic, retain) UIImageView* rightImage;

- (void)setOn:(BOOL)on animated:(BOOL)animated;

@end
Now lets see implementation. Below is code for initialising the UISwitch with custom rect. You can also see we are adding On and Off image as left and right subview to switch.
-(id)initWithFrame:(CGRect)rect
{    
    if ((self=[super initWithFrame:rect])) {
 [self awakeFromNib];
    }
    return self;
}

-(void)awakeFromNib
{
    [super awakeFromNib];
 
    self.backgroundColor = [UIColor clearColor];
    
    [self setThumbImage:[Util imageNamed:@"switch"] 
        forState:UIControlStateNormal];
    [self setMinimumTrackTintColor:[UIColor clearColor]];
    [self setMaximumTrackTintColor:[UIColor clearColor]];
    
    self.minimumValue = 0;
    self.maximumValue = 1;
    self.continuous = NO;
 
    self.on = NO;
    self.value = 0.0;
 
    self.leftImage = [[UIImageView alloc] initWithFrame:self.frame];
    self.leftImage.image = [Util imageNamed:@"on"];
    [self addSubview: self.leftImage];
    [self.leftImage release];
    
    self.rightImage = [[UIImageView alloc] initWithFrame:self.frame];
    self.rightImage.image = [Util imageNamed:@"off"];
    [self addSubview: self.rightImage];
    [self.rightImage release];
}

Now you should be able to see UISwitch with custom images, we now need to add code required to on and off switch from code and change image accordingly.
- (void)setOn:(BOOL)turnOn animated:(BOOL)animated;
{
    on = turnOn;
 
    if (animated) {
 [UIView beginAnimations:@"UICustomSwitch" context:nil];
 [UIView setAnimationDuration:0.2];
    }
 
    if (on) {
 self.value = 1.0;
        self.rightImage.hidden = YES;
        self.leftImage.hidden = NO;
    } else {
 self.value = 0.0;
        self.rightImage.hidden = NO;
        self.leftImage.hidden = YES;
    }
 
    if (animated) {
 [UIView commitAnimations]; 
    }
}


Now finally we also have to add code to enable interaction.
- (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{
    [super endTrackingWithTouch:touch withEvent:event];
    touchedSelf = YES;
    [self setOn:on animated:YES];
}

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    [super touchesBegan:touches withEvent:event];
    touchedSelf = NO;
    on = !on;
}

- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
{
    [super touchesEnded:touches withEvent:event]; 
    if (!touchedSelf) {
 [self setOn:on animated:YES];
 [self sendActionsForControlEvents:UIControlEventValueChanged];
    }
}
That's it, I hope this will help.

Sunday, August 16, 2015

The Math Game for iOS

If you have read my previous posts, you might already know I was trying to learn Swift language. While doing so I tried to create a simple game.

Finally I was able to complete the app and was able to publish it as well. You can download app from here.


Below is demo of the game.

You can also get more information about app here.

Sunday, June 28, 2015

Posting score to Game Kit Leader board using swift

As you might already know, I recently started exploring Swift language and now I am trying out GameKit framework. While I have some experience in working with GameKit using Objective C. I wanted to do the same thing using swift. As such there are no API changes while using GameKit with Swift or Objective C. However there are some syntax change.

In this post, I will show how to Authenticate local player using GameKit framework and post score to LeaderBoard defined in iTune Connect Application setting.

Following is code snippet that shows how to Authenticate Local player. This function takes ViewController as argument. Login dialog will be displayed using this View controller. Rest will be taken care by GameKit framework.
func authenticateLocalPlayer(viewController: UIViewController) {
    let localPlayer: GKLocalPlayer = GKLocalPlayer.localPlayer()
    
    localPlayer.authenticateHandler = {(ViewController, error) -> Void in
        if((ViewController) != nil) {
            // 1 Show login if player is not logged in
            viewController.presentViewController(ViewController, animated: true, completion: nil)
        } else if (localPlayer.authenticated) {
            // 2 Player is already euthenticated & logged in, load game center
            self.isGameCenterEnabld = true                
        } else {
            // 3 Game center is not enabled on the users device
            self.isGameCenterEnabld = false
            println("Local player could not be authenticated, disabling game center")
            println(error)
        }
        
    }
    
}
Now we have authenticated local player. So when we are ready to post score to Leader Board. We can use below function. Here we are posting score to "defaultLeaderBoard". Which is identifier of Leader board defined in iTune connect App setting.

func submitScore( score: Int) {
    if( !isGameCenterEnabld ) {
        return;
    }
    
    var sScore = GKScore(leaderboardIdentifier: defaultLeaderBoard)
    sScore.value = Int64(score)
    
    let localPlayer: GKLocalPlayer = GKLocalPlayer.localPlayer()
    
    GKScore.reportScores([sScore], withCompletionHandler: { (error: NSError!) -> Void in
        if error != nil {
            println(error.localizedDescription)
        } else {
            println("Score submitted")
            
        }
    })
}
That's it. Hope this will be useful.

Friday, June 5, 2015

Hiding status bar in iOS8 using Swift

I recently started learning swift, while learning I started to create simple game. I wanted to make my game full screen, but I was unable to hide top status bar from Interface builder. No matter what I change that status bar was always visible.

Buf I found following code snippet, if you add this code in your View Controller file, you can easily hide status bar.
override func prefersStatusBarHidden() -> Bool {
    return true;
}
Following how my ViewController file looks after adding this code.
class ViewController: UIViewController {
        
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    override func prefersStatusBarHidden() -> Bool {
        return true;
    }
}
That's it. Hope this will be hopeful.

Saturday, January 24, 2015

Notification on property change in iOS SDK

I have used QML quite a lot in my projects and there is one quite nice feature in QML that makes implementation quite easy. The feature is Property change notification.

Apple iOS SDK also similar mechanism named Key-Value Observing mechanism. Here is Apple's documentation for the same.

Following is simple code which demonstrate how we can use Key-Value Observer API to get notification on property changes. First we need to register observer and in which property observer is interested in. Code shows, class "self" is interested in property change event from propertyOwner for "isPlaying" property.
[propertyOwner addObserver:self
    forKeyPath:@"isPlaying"
       options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
       context:NULL];
Now, we have registered observer for property change, we need to implement method which will be called in case of property is changed. Following code shows the same. We need to check which object sent event and for which property, then we can take appropriate action.
- (void) observeValueForKeyPath:(NSString *)path ofObject:(id) object change:(NSDictionary *) change context:(void *)context
{
    // this method is used for all observations, so you need to make sure
    // you are responding to the right one.
    if (object == propertyOwner && [path isEqualToString:@"isPlaying"]) {
        // now we know which property is modified
    }
}
When we are done and don't need notification any more we can remove observer. Below is code for the same. It's safe to use try and catch as we might get exception if we try to remove observer when none is registered.
    @try{
        [propertyOwner removeObserver:self forKeyPath:@"isPlaying"];
    }@catch(id anException){
        //do nothing, obviously it wasn't attached because an exception was thrown
    }
Now whenever "propertyOwner" changes's "isPlaying" property then "self" will get notification and "observeValueForKeyPath" method will get called.

Saturday, December 20, 2014

Resolving "_clock$UNIX2003", referenced from" error

I was trying to build Unity 3D project for simulator SDK. I wanted to get different screen size screen shot. But when I tried to build it I got following build error.
_clock$UNIX2003", referenced from
I found one work around to resolve this issue. We need to add following patch to main.mm file.
#include <time.h>

// "_clock$UNIX2003", referenced from:
//Temporary hack for building Simulator Project for Unity
extern "C"
{
    clock_t
    clock$UNIX2003(void)
    {
        return clock();
    }
}
Once I added above patch build started working fine for me and I was able to run project on Simulator.

Saturday, September 13, 2014

Creating array of IBOutlet

Sometimes you want to enable/disable bunch of buttons together or perform other such activities on bunch of UI elements created using Interface Builder.

I recently needed to perform similar operation on bunch of button for iOS game I am working on. For this kind of operation, its easier to create array of IBOutlet which can be created using IBOutletCollection. Following is my code, which create IBOutletCollection of UIButtons and then enable/disbale them together.
@interface MyViewController : UIViewController {
    IBOutletCollection(UIButton) NSArray *buttons;
}
in MyViewController.m, we can use buttons as below.
-(void) enableUI:(BOOL) enable {    
    for( UIButton* button in buttons){
        button.enabled = enable;
    }    
}
Only thing missing now is, connecting UIButtons created using Interface Builder to IBoutletCollection. We need to do this from Interface Builder, process is similar to connecting UI Elements from Interface Builder to IBOutlet.

Following snaps describes the required process. I created three buttons on view.


You can connect IBoutletCollection to UIButton as shown in below snap.


And you can repeat above process to connect more UIButton with IBOutletCollection.

That's it.

Saturday, November 23, 2013

Using NSOperationQueue in iOS SDK

Sometimes we need to perform some task in different thread or in background. NSOperationQueue is quite handy for such purpose in iOS.

You can easily add operation you need to perform in queue just like any other object and NSOperationQueue queue will take care of its execution. You can also add operation in NSOperationQueue by specifying code block, and in many situations that's quite useful.

 Following code sample shows how we can create NSOperationQueue.
- (id)init
{
    if ((self = [super init]))
    {
        _operationQueue = [[NSOperationQueue alloc] init];
        //[_operationQueue setMaxConcurrentOperationCount:1];
    }
    return self;
}

- (void)dealloc
{
    [_operationQueue release];
    [super dealloc];
}

Below code shows how we can add operation to NSOperationQueue by code block.
- (void)requestFinished:(ASIHTTPRequest *)request {
        
    [_operationQueue addOperationWithBlock:^{
        
        //perform some useful task
        
    }];
}
   -(void) processEntries:(NSArray*) entries
   {
   }

   [_operationQueue addOperationWithBlock:^{
     [self processEntries:entries];
   }];

Friday, September 6, 2013

Reading file from resource in iOS

I was working on creating some utility function for iOS App. I required to create a File in resource and read it. File contains some words separated by new lines. I wanted to read those words and create array of those.

Its quite simple but though to share it.

Following how its done.

        
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"keywords_en" ofType:@"txt"];
NSError *error = nil;
NSString *keywordsStr = [NSString stringWithContentsOfFile: filePath encoding:NSUTF8StringEncoding error:&error];

NSArray* keywordArray = [[keywordsStr componentsSeparatedByString:@"\n"]retain];

Thursday, November 29, 2012

Making app iPhone5 compatible

I recently ported my iPhone app to iPhone5. I required to change quite a few things. Porting experience was not that much smooth as I was expecting.

In this post I am listing what all changes I made to make my universal app iPhone5 compatible.

Enable iPhone5 support

If you have not done anything to your application for iPhone5 support, it should work fine but your app will be launched in letterbox mode. I mean you will see black area around your app.

If you want to remove those black bar and want to use whole iPhone5 screen then you need to supply iPhone5 specific launch image. Image name should be Default-568h@2x.png and resolution should be 640x1136.

When you supply this image, iOS6 knows that your app is iPhone5 resolution compatible.
You can supply that image using project screen.



Once this is done your application will be able to use whole screen area.

You will also need to create other background image with above resolution, however they will not be used by default. You will need to load and display them manually.

Detecting iPhone5

While porting we will need to detect if phone is iPhone5 or not. I am using following code for detecting iPhone5.

+(BOOL) isTall
{
   return  ([ [ UIScreen mainScreen ] bounds ].size.height == 568);
}

Changes in App Delegate

There are some changes in iOS6 to handle orientation change.

In your app delegate class you need to use UIWindow's setRootViewController api to set view controller, rather than using addSubview

Now my applicationDidFinishLauncing method looks like following. I also required to create UIWindow instance manually else touch event was not working properly.

- (void)applicationDidFinishLaunching:(UIApplication *)application 
{        
    self.window = [[[UIWindow alloc] initWithFrame:
       [[UIScreen mainScreen] bounds]] autorelease];
    
    self.viewController = [[ViewController alloc] 
       initWithNibName:@"ViewController" bundle:nil];
    
    if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0)
    {
        // for older version
        [window addSubview: viewController.view];
    }
    else
    {
        // use this method on ios6
        [window setRootViewController:viewController];
    }
    [window makeKeyAndVisible];
}

Handling Orientations

Api to detect orientation change is also changed in iOS6. shouldAutorotateToInterfaceOrientation method is replaced by supportedInterfaceOrientations and shouldAutorotate in iOS6.

I left implementation of shouldAutorotateToInterfaceOrientation method as it is as those will be used for old platform.

Following is how I handled the orientation change.

// For old version
- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight ||
            interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}

// for iOS6
- (NSUInteger) supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskLandscape;
}

-(BOOL) shouldAutorotate {
    return YES;
}

Handling nib file

My application is universal application and I have different nib file for iphone and ipad. There are many view for my application and each view has background and different layout. For iPhone5, you either have to create separate nib file to handle iphone5 specific layout and background image. Or you can go ahead with auto layout but this will work only for iOS6 and onwards.

I wanted to support old platform in the same code base so I ended up creating separate nib file for iPhone5 and specified iphone5 specific background and layout manually.

I am using following code for loading different nib file according to platform.

+(NSString*) getPlatformNibName:(NSString*) origNibName
{
    NSString* fileName = origNibName;
    if( [Util isIPad] == YES ) {
        fileName = [fileName stringByAppendingString:@"-iPad"];
    } else if( [Util isTall] == YES ) {
        fileName = [fileName stringByAppendingString:@"-iphone5"];       
    }
 
    return fileName;
}
After making these changes, my application was working fine for iPhone5.

Saturday, March 19, 2011

Custom UIAlertView in iPhoneSDK

Recently while working on personal project I need to customizing UIAlertView. My requirement was just to add image on UIAlertView everything else should be same.

For that I could have derived UIAlertView and could have provided custom drawing to put image, but instead I used following hack because i thought it was fast.

Here is code if you find it useful.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hack!" 
      message:@"Hacking alert view\n\n\n\n\n" 
     delegate:nil 
     cancelButtonTitle:@"OK" 
     otherButtonTitles:nil];
 
    UIImageView *imageView = [[UIImageView alloc] 
        initWithFrame:CGRectMake(110, 80, 66, 66)];
 
    NSString *path = [[NSString alloc] initWithString:[[
[NSBundle mainBundle] resourcePath] 
stringByAppendingPathComponent:@"images.jpg"]];

    UIImage *bkgImg = [[UIImage alloc] initWithContentsOfFile:path];
    [imageView setImage:bkgImg];
    [bkgImg release];
    [path release];
 
    [alert addSubview:imageView];
    [imageView release];
 
    [alert show];
    [alert release];

Here is output.

Sunday, February 13, 2011

Posting message to facebook wall using iPhone SDK

UPDATE: I have posted my sample application code here. Please visit code fore more information.

Recently I was working on iPhone project that required to post message on Facebook wall.

There is already official facebook API for iOS SDK, which we can use for interacting with Facebook.

You can download Facebook API from GitHub repository using following command.
git clone git://github.com/facebook/facebook-ios-sdk.git

To use downloaded facebook API, you need to bring all facebook API source code under your project. To do this you can just drag it's src folder and drop it under your project in XCode.

Before you start coding, you need a valid facebook application id, you can get one from Developer App. And you need to add this App ID in "fbYOUR_APP_ID" format to your project's .plist file like shown in following snapshot.


Now you are ready to use Facebook iPhone SDK. Main interface class to invoke Facebook API is "Facebook". Following is code to use Facebook class to login and autorize application to use user's facebook account.
facebook = [[Facebook alloc] initWithAppId:@"YOUR_APP_ID"];
   NSArray* permissions =  [NSArray arrayWithObjects:@"read_stream", 
    @"publish_stream", nil];
   [facebook authorize:permissions delegate:self];
With read_stream we can access user's basic account information and with publish_stream we can post to user's wall and make comment.

To authorization to complete successfully we need to implement application:handleOpenURL: method from UIApplicationDelegate and forwad call to facebook API. Like shown in below code.
return [facebook handleOpenURL:url]; 
So everything goes fine then you should be able to retrieve user's account information and post to user's wall as well.

Now to post message to user's wall you can use following code.
NSMutableDictionary* params = [[NSMutableDictionary alloc] 
initWithCapacity:1]
 [params setObject:@"Testing" forKey:@"name"];
 [params setObject:@"IMAGE_URL" forKey:@"picture"];
 [params setObject:@"Description" forKey:@"description"];
 [facebook requestWithGraphPath:@"me/feed" 
        andParams:params 
    andHttpMethod:@"POST" 
      andDelegate:self];
Here "me/feed" is used to post message to logged in user's wall, if you want to post to some other user's wall using logged in user's account then use need to use "USER_ID/feed" instead.

Saturday, February 5, 2011

Playing sound with iPhone SDK

Today I learned to play sound with iPhone SDK, this is first time I worked with sound instead of graphics. So posted my experience here.

In case you need to play short sound in your iPhone App for application action like button click or something similar you can try following code sample.

First of all you need to add Audio Toolbox framework to your project. You can add it like shown in below snap. Right click on Frameworks -> Add -> Existing Frameworks...



After adding audio framework, you can use AudioServices API to play sound. You will need to import AudioToolbox/AudioServices.h file to your header file.

#import <AudioToolbox/AudioServices.h>

Then we need to create system sound id using audio service API like shown in below code.

SystemSoundID soundId;
NSString* soundPath = [[NSBundle mainBundle] pathForResource:@"Sound4" ofType:@"wav"];
CFURLRef soundUrl = (CFURLRef) [NSURL fileURLWithPath:soundPath];
AudioServicesCreateSystemSoundID(soundUrl, &soundId);

After creating system sound id, we can use that id to play sound using following code,

AudioServicesPlaySystemSound(soundId);

Now code part is done, you still need to add actual sound file to resources. After adding sound file to resource you can run your application to play sound.

Friday, February 4, 2011

Saving custom structure in NSMutableDictionary/NSMutableArray with iPhone SDK

Recently while working on iPhone code, I required to store my custom structure in to NSMutableDictionary.

Well, NSMutableDictioary only store object derived from NSObject, so either we can make our structure, a class which is derived from NSObject and that's quite heavy and inefficient solution.

Better solution is to store custom structure in NSValue object and save NSValue to NSMutableDictionary.

As apple document suggest, The purpose of NSValue is to allow items of int, float, and char, pointers, structures and object ids data types to be added to collection objects such as instances of NSArray or NSSet, which require their elements to be objects.

Following is simple code that show how custom structure can be store in NSMutableDictionary.
Creating instance of NSMutableDictionary

NSMutableDictionary *map = [[NSMutableDictionary alloc] initWithCapacity:1];


Code to save structure in NSMutableDictionary.

MyStruct myStruct;
myStruct.someInt = 100; myStruct.someBool = NO;
NSValue* valueForStruct = [NSValue valueWithBytes:&myStruct objCType:@encode(MyStruct)];
[map setObject:valueForStruct forKey:@"MyStruct"];


Code to retrieve structure from NSMutableDictionary.

NSValue* valueForStruct = [map objectForKey:@"MyStruct"];
MyStruct myStruct;
[valueForStruct getValue:&myStruct];
NSLog(@"int val:%i, bool val:%i",myStruct.someInt, myStruct.someBool);

Though, it's not that difficult i thought to share this, hope it will help.

Sunday, August 8, 2010

Creating class instance from NSString in iPhone SDK

In my post Creating object dynamically from class name in Qt  I tried to create class instance from string in Qt. I thought if same can be done in iPhone SDK or not.

In iPhone SDK we can create class instance from class name using NSClassFromString function.

My sample code to test  NSClassFromString is as below.

My base class for dummy parsing

@interface Parser : NSObject {
}
-(void) parse;
@end

@implementation Parser
-(void) parse
{
NSLog(@"Parser::parse");
}
@end

Two derived class, which actually just print and dose nothing useful

@interface Parser1 : Parser {
}
@end

@implementation Parser1
-(void) parse
{
NSLog(@"Parser1::parse");
}
@end

@interface Parser2 : Parser {
}
@end

@implementation Parser2

-(void) parse
{
NSLog(@"Parser2::parse");
}
@end

and after dummy code, some useful code which does actual work and test code for testing

-(void) parse:(NSString*) aParserName
{
NSLog(@"trying to parse for %@", aParserName);
Parser* parser = [[NSClassFromString(aParserName) alloc] init];
[parser parse];
[parser release];
}

-(void) test
{
[self parse:@"Parser1"];
[self parse:@"Parser2"];
}

and finally output

2010-08-08 23:23:43.050 Test[2330:207] trying to parse for Parser1
2010-08-08 23:23:43.052 Test[2330:207] Parser1::parse
2010-08-08 23:23:43.054 Test[2330:207] trying to parse for Parser2
2010-08-08 23:23:43.055 Test[2330:207] Parser2::parse

Tuesday, August 3, 2010

Storing custom object and array in NSUserDefaults

In one of my recent program I required to save application state. Easiest solution to save application state in iPhone is to use NSUserDefaults.

In my application I was creating some custom object and array which store custom object and I required to save those in NSUserDefaults

Initially I struggled with this but finally got solution, so though to share it.

First of all, if you want to save your custom object in NSUserDefaults than it should follow NSCoding protocol.

So your custom class should implement NSCoding protocol like following.

@interface MyClass : NSObject <NSCoding>{
BOOL someFlag;
}

@end

#import "MyClass.h"

@implementation MyClass

- (void) encodeWithCoder:(NSCoder *)coder 
{ 
    //uncomment following if super class is following NSCoding protocol
    //[super encodeWithCoder:coder];
    [coder encodeBool:someFlag forKey:@"SomeFlag"];
}

- (id) initWithCoder:(NSCoder *)coder 
{
    //uncomment following if super class is following NSCoding protocol
    //self = [super initWithCoder:coder];
    self = [super init];
    if( self ) 
    {         
        someFlag = [coder decodeBoolForKey:@"SomeFlag"];
    }    
    return self;
}

@end

Now to store and restore above defined custom class in NSUserDefaults, we can use following code as shown in saveState and restoreState function.

#import "MyClass.h"

@interface Controller : NSObject {
    MyClass* myClass;
    NSMutableArray* myClassArray; 
    int currentState;
}

- (void) saveState;

- (void) restoreState;

@end

#import "Controller.h"

@implementation Controller

- (void) saveState 
{    
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    
    NSData* myClassData = [NSKeyedArchiver archivedDataWithRootObject:myClass];
    [defaults setObject:myClassData forKey:@"MyClass"];
    
    NSData* myClassArrayData = [NSKeyedArchiver archivedDataWithRootObject:myClassArray];
    [defaults setObject:myClassArrayData forKey:@"MyClassArray"];
    
    [defaults setInteger:currentState forKey:@"CurrentState"];
}

- (void) restoreState 
{    
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    
    NSData* myClassData = [defaults objectForKey:@"MyClass"];
    myClass = [NSKeyedUnarchiver unarchiveObjectWithData:myClassData];
    
    NSData* myClassArrayData = [defaults objectForKey:@"MyClassArray"];    
    NSArray *savedMyClassArray = [NSKeyedUnarchiver unarchiveObjectWithData:myClassArrayData];
    if( savedMyClassArray != nil ) 
        myClassArray = [[NSMutableArray alloc] initWithArray:savedMyClassArray];
   else
myClassArray =  [[NSMutableArray alloc] init];
    
    currentState = [defaults integerForKey:@"CurrentState"];
}

@end

Tuesday, July 27, 2010

Detecting Long press( Tap and hold) on iPhone application

I was creating one game for iPhone and I required to detect Tap and Hold (Long press ) gesture in application. After trying a bit and reading some documentation, I found following solution. Solution is to perform Selector with some delay, and cancel Selector if touch has ended before enough time is passed.

Following is code from my application.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"touch began");
[self performSelector:@selector(longTap) withObject:nil afterDelay:1.0];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"touch ended");
[NSObject cancelPreviousPerformRequestsWithTarget:self 
selector:@selector(longTap) object:nil];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"touches moved");
[NSObject cancelPreviousPerformRequestsWithTarget:self 
selector:@selector(longTap) object:nil];
}

-(void) longTap 
{
NSLog(@"handle long tap..");
}

Hope this helps...

Friday, May 14, 2010

View switching on iPhone SDK


While creating sample game for iPhone I required to create menu page for game. Here I am putting down code that I used to create menu for my sample game.

First create a view based application.


Then created menu view as following, with two button that will load new view.

Then add new view controller, I named new view as first view and add button on first view that will switch view to menu screen.


Now connect buttons to message that get activated when button is pressed and when button connection is ready then we can write code that will enable view switching. 

In menu view controller, I used following code to load first view. 

- (IBAction) siwthToView1:(id) sender {        

    FirstView *firstView = 
[[FirstView alloc] initWithNibName:@"FirstView" bundle:nil];

    [self.view addSubview: firstView.view];

}

addSubView message will add new view on view stack and display new view on screen.

Now, in first view I used removeFromSuperview message of UIView to go back to menu view.

removeFromSuperview will remove current view from view stack and displays the superview.


- (IBAction) back:(id) sender {

    [self.view removeFromSuperview];
}

So this was all, by using this simple code I implemented my game's menu page.



Tuesday, April 27, 2010

Creating custom view for iPhone

Currently I am trying to create simple game for iPhone. To create game first thing I needed to learn is to create custom view and custom drawing. So here I am putting down my learning in hope that it will help some one who started learning iPhone development.

I started with creating new window based project and named it CustomView.


Then I created new class named CustomView and derived it from UIView.


After creating class derived from UIVIew, we need to make sure that application's window add newly created class as its subview like shown in code below. 

- (void)applicationDidFinishLaunching:(UIApplication *)application {   

    CustomView *view = [[CustomView alloc] initWithFrame:window.frame];
   
    // Override point for customization after application launch
    [window addSubview:view];
    [window makeKeyAndVisible];
}

Then finally implement drawRect with custom drawing code. Here is my code with comment, in following code I am drawing a text, a rectangle , a circle and an Image.

- (void)drawRect:(CGRect)rect {
    // Drawing code
    //acquire graphics context
    CGContextRef ctxt = UIGraphicsGetCurrentContext();
   
    //set brush and set brush color to yellow
    CGContextSetFillColorWithColor(ctxt, [[UIColor yellowColor] CGColor]);
   
    //create string to draw
    NSString *hello = @"Hello World!";
    //create font to be used
    UIFont* font = [UIFont systemFontOfSize:20];
   
    //find horizontal center position for text
    int xLocation = ([self frame].size.width / 2) - ( [hello sizeWithFont:font].width /2 );
    [hello drawAtPoint:CGPointMake( xLocation, 100 ) withFont:[UIFont systemFontOfSize:16.0]];
   
    //draw rect
    CGContextFillRect(ctxt, CGRectMake(50, 50, 50, 50));
    //change brush color to green and draw circle
    CGContextSetFillColorWithColor(ctxt, [[UIColor greenColor] CGColor]);
    CGContextFillEllipseInRect(ctxt, CGRectMake(150, 150, 50, 50));
   
    //draw image
    UIImage *image = [UIImage imageNamed:@"red-ind.png"];
    [image drawAtPoint:CGPointMake( 100,200)];
}

So end result looks like following.

Wednesday, April 21, 2010

Creating UIButton manually on IPhone SDK

Recently I started to learn iPhone development just for fun. iPhone sdk comes with great IDE which has great tool like memory leak finder, profiler, interface builder and other such tool. To create UI for iPhone application interface builder is great tool, but sometime we need to create control programatically at runtime. I also faced same situation to create UIButton control at runtime.

So here I am sharing my learning to create UIButton at runtime and adding it to view.

In following, I am creating UIButton named customButton, setting its location and size on screen and then image for normal and highlighted state.

UIButton* customButton = [UIButton buttonWithType:UIButtonTypeCustom];
[customButton setFrame:CGRectMake(10,10, 100, 100)];
[customButton setImage:[UIImage imageNamed:@"blue-ind.png"] forState:UIControlStateNormal];
[customButton setImage:[UIImage imageNamed:@"red-ind.png"] forState:UIControlStateHighlighted];
Then I am specify what function needed to be called when button get pressed using addTarget method of UIButton.

[customButton addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
Finally adding button to view.

[self.view addSubview:customButton];
Now when above button is clicked, btnClicked method will be get called. I have used following declaration and definition for btnClicked method.

-(void) btnClicked ;

-(void) btnClicked {
    NSLog(@"Custom button clicked");
}
Here is output of above code.