Category Archives: Objective-C

Handling Files in iOS

Hi All,

In Todays article we will see how we can handle files in Objective C.

The list of the methods used for accessing and manipulating files are listed below. Here you have to replace the FilePath1, FilePath2 and FilePath strings to our required full file paths to get the desired action.

NSFileManager *fileManager = [NSFileManager defaultManager];
 //Get documents directory
 NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains
 (NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];
 if ([fileManager fileExistsAtPath:@""]==YES) {
           NSLog(@"File exists");

Comparing two file contents

 if ([fileManager contentsEqualAtPath:@"FilePath1" andPath:@" FilePath2"]) {
         NSLog(@"Same content");

Check if writable, readable and executable

 if ([fileManager isWritableFileAtPath:@"FilePath"]) {
         NSLog(@"File isWritable");

  if ([fileManager isReadableFileAtPath:@"FilePath"]) {
          NSLog(@"File isReadable");

 if ( [fileManager isExecutableFileAtPath:@"FilePath"]){
          NSLog(@"File is Executable");

Move file

 if([fileManager moveItemAtPath:@"FilePath1" toPath:@"FilePath2" error:NULL]){
          NSLog(@"File Moved successfully");

Copy file

if ([fileManager copyItemAtPath:@"FilePath1" toPath:@"FilePath2" error:NULL]) {
          NSLog(@"File Copied successfully");

Remove file

 if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) {
          NSLog(@"File Removed successfully");

Read file

 NSData *data = [fileManager contentsAtPath:@"Path"];

Write file

 [fileManager createFileAtPath:@"" contents:data attributes:nil];

How to add info button to right side or leftside of navigationbar in iPhone?

    UIButton* infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
    [infoButton addTarget:self action:@selector(showInfoView:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:infoButton];

Adding button action function.

- (IBAction)showInfoView:(id)sender {

Random Integer array without repetition in Objective C Iphone

This sample code generates a random number and checks whether its already present in the array.
If yes then it will not add else it will add, thus generating a random array without duplicates.

-(NSMutableArray *) generateRandomArray : (int) max{
    NSMutableArray *randArray = [NSMutableArray new];
    for (int k = 0; k < max; k++) {
       int r = arc4random() % max;
        if([randArray containsObject:[NSString stringWithFormat:@"%d", r]]){
            [randArray addObject:[NSString stringWithFormat:@"%d", r]];
    NSLog(@"RAND %@",randArray);
    return randArray;

Please leave your valuable comments if you found this post useful.

How to download an image from a URL in Objective C iPhone?

Download image from URL in iPhone

This method downloads the image from the specified URL and stores in the documents directory and then shown in an ImageView.
Make sure you have an imageview linked with the outlet in the UserInterface.

-(void) downloadImageFromURL :(NSString *)imageUrl{
    NSURL  *url = [NSURL URLWithString:imageUrl];
    NSData *urlData = [NSData dataWithContentsOfURL:url];
    if ( urlData )
        NSLog(@"Downloading started...");
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"dwnld_image.png"];
        NSLog(@"FILE : %@",filePath);
        [urlData writeToFile:filePath atomically:YES];
        UIImage *image1=[UIImage imageWithContentsOfFile:filePath];

Please leave your comments if you found this code useful.

How to create a radioGroup in Android inside a Scrollview?

Here is a sample code that creates a radiobutton group inside a scrollview.
Please make sure you have a scrollview in your UI and its linked.

// This function adds the radio buttons inside the scrollview.
Here I am using some of my variables to generate the count of radio buttons.
Please make sure to change it before using it in your code.

UIRadioButton implementation in iPhone
UIRadioButton implementation in iPhone

NSString *const CHECKED_IMAGE = @"radiochecked.png";
NSString *const UNCHECKED_IMAGE = @"radiounchecked.png";

int y=0;
    for(int optionCount = 0; optionCount < [pracObj.answers count]; optionCount++){
        UIButton *answerCheckBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [answerCheckBtn addTarget:self action:@selector(answerSelected:)
        [answerCheckBtn setTitle:@"" forState:UIControlStateNormal];
        //set background image for button
        answerCheckBtn.backgroundColor = [UIColor clearColor];
        answerCheckBtn.frame = CGRectMake(1.0, y+2, 20,20);
        UIImage *buttonImageNormal = [UIImage imageNamed:UNCHECKED_IMAGE];
        UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
        [answerCheckBtn setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];
        answerCheckBtn.tag = optionCount + ANSWERTAG_STARTING;
        UILabel *answerLabel = [UILabel new];
        answerLabel.tag =  optionCount+100;
        answerLabel.text = [[pracObj.answers objectAtIndex:optionCount] stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
        answerLabel.lineBreakMode = NSLineBreakByWordWrapping;
        answerLabel.numberOfLines = 1;       
        answerLabel.frame = CGRectMake(30, y+2, 300.0, 20.0);
        [answerLabel sizeToFit];
        [answerLabel setFont:[UIFont systemFontOfSize:10]];
        [answersScrollView addSubview:answerCheckBtn];
        [answersScrollView addSubview:answerLabel];

And click of each radio button you can cal this function to reset the image.

    UIButton *curBtn = (UIButton*) sender;
    NSLog(@"DYN MEthod Clckd %d", curBtn.tag);
    UIImage *buttonImageNormal = [UIImage imageNamed:CHECKED_IMAGE];
    UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
    [curBtn setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];
    [self clearButtons:curBtn.tag];

-(void) clearButtons:(int) curTag
    int totalAnsCount = [curPracticeQuestionObj.answers count];
    for (int y = ANSWERTAG_STARTING; y < (ANSWERTAG_STARTING + totalAnsCount); y++) {
        if (y != curTag) {
            UIButton *otherButton = (UIButton *)[answersScrollView viewWithTag:y];
            UIImage *buttonImageNormal = [UIImage imageNamed:UNCHECKED_IMAGE];
            UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
            [otherButton setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];

How to split a string using a delimiter in iPhone and add it to a mutable array?

Here is a simple code that does this..

-(NSMutableArray *) getAnswers :(NSString *) yourstring{
    NSMutableArray *answers = [NSMutableArray new];
    NSArray *parts = [[yourstring componentsSeparatedByString:@","];
    for(NSString *str in parts){
        [answers addObject:str];
    NSLog(@"RET answers %@", answers);
    return answers;

After splitting the string with “componentsSeparatedByString” the parts are added to a NSMutableArray using addObject.

Apple fined by China court for copyright violation

A court in China has ordered Apple to pay compensation to eight Chinese writers and two companies for violating their copyrights.

They had claimed that unlicensed electronic versions of their books had been sold on Apple’s online store.

The court ordered Apple to pay them 1.03m yuan ($165,000; £100,000) in compensation, according to the official news agency Xinhua.
… Read more from here.

How to find your Google Plus ID

This is so simple

1. Go to your Google + account (

2. Click on the Profile icon on the Left.

3. If you look at the URL in the address bar, it should look something like this:

4. The long numerical string in the URL is your Google+ ID. Here is CoderzHeaven’s from the URL above:


Google + CoderzHeaven

How to move a body manually in Box2D? or Give a force to a body in Box2D, iPhone.

This is a sample code to move a body in Box2D .
First you have to make a body with variable name “moving_rec” and call the below function in a schedular at regular intervals.

-(void) moveBody{
       b2Vec2 force = b2Vec2(0,0);
       force = b2Vec2(0,3);       //Giving the x an y to negative will move the body in opposite direction.
       moving_rec->SetLinearVelocity(force); //set Linear velocity for moving in a constant speed.

Please leave your comments on this post.

Pause And Resume iPhone Game Using Cocos2D

More than usually we need to apply the functions of Pause and Resume/Play for our games. In Mac’s cocos2D programming it’s more than simple. Simply use the following code for Pause & Resume where ever you want!

/*For Pausing the game*/

[[CCDirector sharedDirector] pause];
[self pauseSchedulerAndActions]; //Call for pausing all schedulers and actions

/*For Resuming/Playing back the game*/

[[CCDirector sharedDirector] resume];
[self resumeSchedulerAndActions]; // Call for resuming all schedulers and actions


Collision detection in Box2D


Collision can be detected simply using the following lines of code with box2D.

if((contact.fixtureA == aimFixture && contact.fixtureB == tarFixture) ||
     (contact.fixtureA == tarFixture&& contact.fixtureB == aimFixture ))
        NSLog(@"Collision between aim fixture and target fixture detected!");

Here aimFixture & tarFixture are two custom fixtures whose collision you want to find out.


Using of CCWaves in iPhone

CCWaves is one of the interesting functionalities in Cocos2D iphone.
Check out this following snippet to see how it works.

id my_wavesAction = [CCWaves actionWithWaves:7 amplitude:25 horizontal:NO
                                                               vertical:YES grid:ccg(15,10) duration:10];
[my_sprite runAction: [CCRepeatForever actionWithAction:my_wavesAction n]];

Please leave your valuable comments on this post………………….

How to get Device Orientation in Cocos2D, iPhone in Objective C?

Hello all……
We may need to know that what is your current device orientation.
Using the below code you can do this.

if([[UIDevice currentDevice] orientation] == kCCDeviceOrientationPortrait) {
            NSLog(@"Device is now in Portrait Mode");
else if ([[UIDevice currentDevice] orientation] == kCCDeviceOrientationLandscapeLeft) {
            NSLog(@"Device is now in LandscapeLeft Mode ");
else if ([[UIDevice currentDevice] orientation] == kCCDeviceOrientationLandscapeRight) {
            NSLog(@"Device is now in LandscapeRight Mode");
else if([[UIDevice currentDevice]orientation] ==
  kCCDeviceOrientationPortraitUpsideDown) {
            NSLog(@"Device is now in PortraitUpsideDown Mode");
ss="Apple-style-span" style="font-weight: normal;">

Note: If you have to explicitly set the orientation of your phone to any of the above you can set this in the appDelegate.m file. You can put an “||” (OR) symbol in between to set more than one.

Please leave your valuable comments if this post was useful…..

Simulate a Balloon in Box2D, iPhone or ANDROID

Sometimes you may want your body to act against the gravity of the world.
One method to do this is described below.
First what you have to do is to make a body in the shape of a circle and give it the image of a balloon as the userdata.

Then in the tick function write this code.
This method of applying the force is called “The antagonist forces method”
By this method we are giving an upward force to only our balloon body irrespective of the gravitational force.
After running the code you will see your body floating in air like a balloon.

for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
        if (b->GetUserData() != NULL) {
               if (b==baloonBody) {
                         b->ApplyForce( b2Vec2(0.0,9.8*b->GetMass()),b->GetWorldCenter()); // here 0.0 is x, 9.8 is y (the gravity)

Note: Try to change the value 9.8 to higher if you have given your world’s gravity as 9.8. It will produce a balloon effect.
Please leave your comments if this post was useful……….

Sprite Animations Without Sprite Sheets

You can simulate any animations if you have a sequence of images which makes the illusion of that
animations and rendering those images to the screen. In cocos2D it can be done in two ways, with sprite sheet
animation and without sprite sheets. Here we are going to see how it can be done with out sprite sheet.

CCAnimation *sitDown = [CCAnimation animationWithName:@"sitDown" delay:0.1f];

[sitDown addFrameWithFilename:@"sit1.png"];
[sitDown addFrameWithFilename:@"sit2.png"];

[mySprite addAnimation:sitDown];

id sitAction = [CCAnimate actionWithAnimation:sitDown restoreOriginalFrame:YES];

[yourSprite runAction:sitAction];

Here CCAnimation holds a series of images known as Frames and CCAnimate is simply the action which will run the
CCAnimation. Simple.

Suppose that we have two images named, sit1.png and sit2.png which simulates a sitting animation of our sprite. First
we have added that images/frames to our CCAnimation object sitDown. Then we CCAnimate our CCAnimation frames and
deploy those actions to our sprite. We can set the delay time between the individual frames in CCAnimation. Also we can restore the original image before sprite animation after animatin completes or not!That’s it.

We will later see in here how Sprite Animations can be done by using Sprite Sheets. Keep in touch.


How to set UITableView background Image ?


Setting a background image to the UITableView will make it looks great! Use the following code to set a background image to a UITableView.

UIImage *bgImage= [UIImage imageNamed:@"sampleImage.png"];

UIImageView *bgView= [[UIImageView alloc] initWithImage:bgImage];

urTblView.backgroundView = bgView;

Here ‘urTblView’ is your UITableView.

How to Show Cocos2D Particle Effects Repeatedly ?


For showing particle effects repeatedly in Cocos2D, use the sample code.

CCParticleSystemQuad *yourParticleEffect = [CCParticleSystemQuad particleWithFile:@"yourEffect.plist"];

[self addChild:yourParticleEffect z:5];

This will show the effect ‘yourEffect’ repeatedly in your game.

How to make UITextField a Password Field in iPhone ?


In order to make a UITextField a Password Field / Password Mode do the following.

In your .h class file,

IBOutlet UITextField *urPassword;

In your .m class file,

urPassword.secureTextEntry = YES;

This will make your UITextField in a Password entry mode or a Password Field.