Category Archives: iPhone

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];

Delegates in iOS – A Simple Example

Hi All,

Today I am going to talk about iOS Delagates.
This example shows how to write a common delegate for a mail composer in iOS.

First I am going to crate a seperate class for invoking the MailComposer Modal view controller.
The class is named “Common”.

So Create .m and .h files for Common.


#import <Foundation/Foundation.h>
#import <MessageUI/MessageUI.h>

@interface Common : NSObject{
    MFMailComposeViewController *mailComposer;

@property (nonatomic, weak) id <MFMailComposeViewControllerDelegate> delegate;

-(void)sendMail:(UIViewController *) cont : (NSString *) mailSubject : (NSString *) mailBody;

-(void) setDelegate:(id <MFMailComposeViewControllerDelegate>)aDelegate;


Now Go to Common.m and implement the methods.

#import "Common.h"

@implementation Common

@synthesize delegate;

-(void)sendMail:(UIViewController *) cont :(NSString *) mailSubject : (NSString *) mailBody{
    mailComposer = [[MFMailComposeViewController alloc]init];
    [mailComposer setSubject:mailSubject];
    mailComposer.mailComposeDelegate = delegate;
    [mailComposer setMessageBody:mailBody isHTML:NO];
    [cont presentViewController:mailComposer animated:YES completion:nil];

-(void) setDelegate:(id <MFMailComposeViewControllerDelegate>)aDelegate{
    if (delegate != aDelegate) {
        delegate = aDelegate;        


Now Go to ViewController.h

We don’t need any declarations inside this class, just need to add the delegate

#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>

@interface ViewController : UIViewController<MFMailComposeViewControllerDelegate>

Now in the implementation class


#import "ViewController.h"
#import "Common.h"

@interface ViewController ()


@implementation ViewController

- (void)viewDidLoad

    Common *com = [Common new];
    [com setDelegate:self];   // Setting the Mail Composer delegate
    [com sendMail:self :@"Mail Subject" :@"Mail Body"];

#pragma mark - mail compose delegate
-(void)mailComposeController:(MFMailComposeViewController *)controller
         didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
    if (result) {
        NSLog(@"Result : %d",result);
    if (error) {
        NSLog(@"Error : %@",error);
    [self dismissViewControllerAnimated:YES completion:nil];

Ok. Now our MailComposer Delegate is implemented. Go on and run the application.

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.

A 4.8 inch iPhone may be on the way

Every iPhone user may be envious on seeing a bigger screen Android Phone.

iPhone 5S

But don’t worry Apple is said to be working on an iPhone with a 4.8-inch screen, a 20% increase in screen size from the iPhone 5S, iPhone 5C and iPhone 5.

Jeffries analyst Peter Misek has issued a research note to investors where he cited supply chain sources in China claiming that Apple will unveil an iPhone with 4.8-inch screen. This model is scheduled to be launched in September next year and will be named iPhone 6, said Misek.

You can read more about the story from here

Apple iPhones may come up with as less as $99 in the future


these are the rumours about the future iphone. Apple is reportedly looking at iPhones with bigger screens and will be releasing the low cost phone in
a range of colors as soon as this year, the ABC News reports.

According to the report, Apple declined to comment on the rumors,
Cook also said the iPhone doesn’t have a larger screen right now for a few reasons.

He said that a large screen today comes with a lot of tradeoffs, adding that people do look at the size, but they also look at things like if the photos show the proper color, the white balance, reflectivity, battery life, brightness, the longevity of the display.

Read more from here

Google to unveil Moto X to take on Apple.


Google bought Motorola in 2011 and ever since there has not been a phone from Google and Motorola.
Now it is that Google will be unveiling Moto X to take on rival Apple.

iPhone overprice tag has not come down since its launch in 2007. This will be a area where Google and Motorola will be targeting.

While Apple’s critics say the once wildly inventive company is running out of ideas, Motorola’s chief executive, Dennis Woodside, has promised to bring “audaciousness” and “innovation” back to mobile computing.

In a future-gazing presentation at the AllThingsD conference in California, Woodside, who has been charged with turning around the company that invented the first mobile phones of the 1980s, said he was also working on wearable technology.

Read complete story from here.

Budget iPhone 5 Coming Soon

iPhone 5

The budget version of Apple’s latest iPhone will cost roughly $330 (£220), priced in order to appeal to young, middle class consumers in countries like China and India.
The claims about the price and the imminent release were made on the Japanese website Macotakara, following on from earlier reports about Apple plans for a cheaper phone.
In January it was reported that the planned new phone will resemble the iPhone 5 from the front but Apple will replace that handset’s aluminium body with a cheaper plastic casing.

Read More from here

iPhone Mini launch this summer

iPhone Mini

A low-priced iPhone makes a lot of sense, Morgan Stanley says, and it even could hit the market this summer.
Katy Huberty, an analyst with the banking firm, noted that after her meetings with Apple Chief Financial Officer Peter Oppenheimer, she’s convinced that innovation remains a top priority for the Cupertino, Calif., electronics giant. She also believes that Apple will increase cash return to shareholders and expand carriers, distribution, and possibly price points to drive iPhone growth.
She noted that a lower priced iPhone makes sense for several reasons:
“iPad Mini is expanding Apple’s customer base with 50 [percent] of purchases in China/Brazil representing new customers to the ecosystem.”
“Chinese consumers show a desire to purchase the latest version of iPhone (instead of discounted older generations).”
“iPhone 4 demand surprised to the upside in the December quarter.”

Read more from here

How to call a function in background in Xcode(iPhone)?

“performSelectorInBackground” will call anyfunction to execute in background and you can also pass string parameters with this method or if you want to pass more params then pass the parameters as an object.

[self performSelectorInBackground:@selector(myBackgroundMethod:) withObject:@"String Params"];

How to Change UIWebview’s background color in iPhone Xcode?

Unlike other UIViews, the UIWebview’s opaque property is set to true by default. That should be set to false for changing the background color.

[myWebView setOpaque:NO];

myWebView.backgroundColor=[UIColor redColor];

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

Which you think is the best – Android or iPhone?

This is a question that has been here since 2007. We know there are many advantages for Android phones and Apple’s iPhone. So what you think, which one is the best.

I will say my personal opinion. And I think Android is the best.

Android vs iPhone

What is your opinion?

Are you an iPhone or ANDROID User?

Why you think one is better than the other from your personal experience?

Do you think Fragmentation is a curse for ANDROID or iPhone?

Paste you opinion here and Let’s see what real phone users are thinking.

New iPhone may be getting Larger screens.


The new iPhone that Apple Inc. is expected to unveil this year is likely to have a larger display than its current models have, with the company ordering bigger screens from its Asian suppliers, people familiar with the matter said.

The new screens measure at least 4 inches diagonally, the people said, compared with 3.5 inches on Apple’s latest model, the iPhone 4S. Production is set to begin next month, the people said. Analysts have predicted that the next iPhone will come out in the fall.

Read more from here..

How to Play Audio using Corona SDK ?


For playing audio – background music or sound effects – using Corona SDK, do the following,

1. Load the audio stream (background music or sound effects)

 backgroundMusic = audio.loadStream("bgm.mp3") 

2. Play the audio

backgroundMusicChannel = backgroundMusic, { channel=1, loops=-1, fadein=5000 }  )  

It will play the background music on channel 1, loop infinitely, and fadein over 5 seconds. Loop 1 will set it to play once!


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.