Category Archives: iPhone

What is @property in iOS mean?

The goal of @property directive in iOS is to create the getters and setters for that object so that you can access it in your program. It allows you to specify the behavior of a public property on a semantic level, and it takes care of the implementation details for you.

This article also tells how you can alter these “getters and setters” that are generated by @property

The @property Directive

Let’s see what happens when we declare an @property directive.

Lets study it with an example

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

@interface Car : NSObject

@property BOOL running;

@end
// Car.m
#import "Car.h"

@implementation Car

@synthesize running = _running;    // Optional for Xcode 4.4+

@end

The compiler generates a getter and a setter for the “running” property.
The default naming convention is to use the property itself as the getter, prefix it with set for the setter, and prefix it with an underscore for the instance variable, like so:

- (BOOL)running {
    return _running;
}
- (void)setRunning:(BOOL)newValue {
    _running = newValue;
}

So when you declare a variable using @property this means that you can call its getter and setter as if it is included in the class interface.

You can also override them in Car.m to supply custom getter/setters, but this makes the @synthesize directive mandatory.
However, you should rarely need custom accessors, since @property attributes let you do this on an abstract level.

so when you call

Car *maruti = [Car new];
maruti.running = YES;                // [maruti setRunning:YES]
NSLog(@"%d", maruti.running);        // [maruti running]

You can also change the default getter and setter like this.


@property (getter=isRunning) BOOL running;

Now the “getter” method is called “isRunning” and “setter” method is “setRunning”


Car *maruti = [[Car alloc] init];
maruti.running = YES;                // [maruti setRunning:YES]
NSLog(@"%d", maruti.running);        // [maruti isRunning]
NSLog(@"%d", [maruti running]);      // Error: method no longer exists

The readonly Attribute

When you specify “readonly” attribute to a variable, compiler omits its its setter method but the “getter” is unaffected.


#import <Foundation/Foundation.h>

@interface Car : NSObject

@property (getter=isRunning, readonly) BOOL running;

- (void)startEngine;
- (void)stopEngine;

@end


// Car.m
#import "Car.h"

@implementation Car

- (void)startEngine {
    _running = YES;
}
- (void)stopEngine {
    _running = NO;
}

@end

@property also generates an instance variable for us, which is why we can access _running without declaring it anywhere (we can’t use self.running here because the property is read-only).


Car *maruti = [Car new];
[maruti startEngine];
NSLog(@"Running: %d", maruti.running);
maruti.running = NO;                      // Error: read-only property

The nonatomic Attribute

Atomicity deals with how properties behave in a threaded environment.
When you have more than one thread, it’s possible for the setter and the getter to be called at the same time.
This means that the getter/setter can be interrupted by another operation, possibly resulting in corrupted data.

Using atomic somewhat means that your variable is thread safe.

Properties declared with @property are atomic by default, and this does incur some overhead.

So if we can do like this if you application is not a multithreaded application


@property (nonatomic) NSString *model;

The strong Attribute

The strong attribute creates an owning relationship to whatever object is assigned to the property. This is the implicit behavior for all object properties, which is a safe default because it makes sure the value exists as long as it’s assigned to the property.

Let’s take a look at how this works by creating another class called Person. It’s interface just declares a name property:


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

@interface Person : NSObject

@property (nonatomic) NSString *name;

@end


// Person.m
#import "Person.h"

@implementation Person

- (NSString *)description {
    return self.name;
}

@end

Above implementation overrides NSObject’s description method, which returns the string representation of the object.

Now we will add a person to the Car Class


// Car.h
#import <Foundation/Foundation.h>
#import "Person.h"

@interface Car : NSObject

@property (nonatomic) NSString *model;
@property (nonatomic, strong) Person *driver;

@end

Now during usage


Person *hari = [Person new];
hari.name = @"hari";

Car *maruti = [Car new];
maruti.model = @"Maruti Swift";
maruti.driver = hari;

NSLog(@"%@ is driving the %@", maruti.driver, maruti.model);
        

Since driver is a strong relationship, the maruti object takes ownership of john.
This ensures that it will be valid as long as maruti needs it.

The weak Attribute

Strong references pose a problem if, for example, we need a reference from driver back to the Car object he’s driving. First, let’s add a car property to Person.h:


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

@class Car;

@interface Person : NSObject

@property (nonatomic) NSString *name;
@property (nonatomic, strong) Car *car;

@end

The @class Car line is a forward declaration of the Car class. It’s like telling the compiler, “The Car class exists, don’t try to find it right now.”

Now use it like this


maruti.driver = hari;
hari.car = maruti;       // Add this line

Now there is a relation b/w maruti and Person and also Person and maruti.
So it is not destroyable by memory management.

This is called a retain cycle, which is a form of memory leak.

But we can fix it by using “weak” attribute like this


@property (nonatomic, weak) Car *car;

The weak attribute creates a non-owning relationship to car.
This allows hari to have a reference to maruti while avoiding a retain cycle.

The copy Attribute

The copy attribute is an alternative to strong. Instead of taking ownership of the existing object, it creates a copy of whatever you assign to the property, then takes ownership of that. Only objects that conform to the NSCopying protocol can use this attribute.

Example


// Car.h
@property (nonatomic, copy) NSString *model;

Now, Car will store a brand new instance of whatever value we assign to model.


Car *maruti = [Car new];
NSMutableString *model = [NSMutableString stringWithString:@"Maruti Swift"];
maruti.model = model;

NSLog(@"%@", maruti.model);
[model setString:@"Maruti Zen"];
NSLog(@"%@", maruti.model);            // Still "Maruti Swift"

The retain Attribute

The retain attribute is the Manual Retain Release version of strong, and it has the exact same effect: claiming ownership of assigned values.
You shouldn’t use this in an Automatic Reference Counted environment.

The assign Attribute

The assign attribute doesn’t perform any kind of memory-management call when assigning a new value to the property.
This is the default behavior for primitive data types, and it used to be a way to implement weak references before iOS 5.
Like retain, you shouldn’t ever need to explicitly use this in modern applications.

Summary

getter= —> Use a custom name for the getter method.
setter= —> Use a custom name for the setter method.
readonly —> Don’t synthesize a setter method, creates only getter method [the trick to make setter method “private” for class users – so only getter method will be visible for compiler. Usually in implementation file this property is redeclared without readonly attribute using custom category so that setter method can be used inside class itself.]
nonatomic —> Don’t guarantee the integrity of accessors in a multi-threaded environment. This is more efficient than the default atomic behavior.
strong —> Create an owning relationship between the property and the assigned value. This is the default for object properties. [synthesized getter method will return ivar directly without locking it for thread-safety]
weak —> Create a non-owning relationship between the property and the assigned value. Use this to prevent retain cycles.
copy —> Create a copy of the assigned value instead of referencing the existing instance.
retain —> Class retains the pointer, the previous value is released

Creating a Custom Alert or PopUp in iOS

Custom PopUp IOS

First we will write a class that extends UIView to create a Custom PopUp

Create a Cocoa file and name it CustomPopUp

You should get two files CustomPopUp.h and CustomPopUp.m

CustomPopUp.h


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

@protocol ClickDelegates;

@interface CustomPopUp : UIView{
    
      UIView *childPopUp;
      id<ClickDelegates> _click_delegate;
      UIViewController *_parent;
    
}

@property (nonatomic, retain) id<ClickDelegates> _click_delegate;
@property (nonatomic, retain) UIViewController *_parent;

-(void) initAlertwithParent : (UIViewController *) parent withDelegate : (id<ClickDelegates>) theDelegate;

-(IBAction)OnOKClick :(id) sender;

-(void) hide;

-(void) show;

@end


// Delegate

@protocol ClickDelegates<NSObject>

@optional

-(void) okClicked;
-(void) cancelClicked;

@end

CustomPopUp.m



#import "CustomPopUp.h"
#import "Util.h"

@implementation CustomPopUp{
    
    float popUpX;
    CGRect popUpRect;
}

@synthesize _click_delegate, _parent;


-(void) initAlertwithParent : (UIViewController *) parent withDelegate : (id<ClickDelegates>) theDelegate{
    
    self._click_delegate = theDelegate;
    self._parent = parent;
    
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;
    CGFloat screenHeight = screenRect.size.height;
    
    CGRect rect = CGRectMake(0, 0, screenWidth, screenHeight);
    self.frame = rect;
    self.backgroundColor = [UIColor clearColor];
    
    childPopUp = [UIView new];
    float popUpHeight = screenHeight/3;
    
    popUpX = 20.0;
    
    popUpRect = CGRectMake(popUpX, (screenHeight - popUpHeight)/2, screenWidth - (popUpX * 2), popUpHeight);
    childPopUp.center = self.center;
    self.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.001, 0.001);
    [self setBorderOnly:childPopUp withBGColor:[UIColor orangeColor] withCornerRadius:5.0 andBorderWidth:0.0 andBorderColor:[UIColor greenColor] WithAlpha:1];
    childPopUp.frame = popUpRect;
    [self addSubview:childPopUp];
  
    [self addLabel];
    
    [self addButton];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(bounce1AnimationStopped)];
    self.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.1, 1.1);
    [UIView commitAnimations];
    
}

-(void) show{

    [self._parent.view addSubview:self];
}

-(void) addLabel{
    
    // Add Label
    UILabel *lblForDisplay=[[UILabel alloc]initWithFrame:CGRectMake(popUpX, popUpX, popUpRect.size.width - popUpX, popUpX)];
    lblForDisplay.backgroundColor=[UIColor clearColor];
    lblForDisplay.textColor=[UIColor blackColor];
    lblForDisplay.text=@"This is a custom Alert";
    [childPopUp addSubview:lblForDisplay];
    
}


-(void) addButton{
    
    // Add Button
    UIButton *okBtn = [[UIButton alloc]initWithFrame:CGRectMake(popUpX, childPopUp.frame.size.height - 50, popUpRect.size.width - 40, 40)];
    okBtn.backgroundColor=[UIColor blueColor];
    [self setBorderOnly:okBtn  withBGColor:[UIColor greenColor] withCornerRadius:5.0 andBorderWidth:0.0 andBorderColor:[UIColor greenColor] WithAlpha:1];
    [okBtn setTitle:@"OK" forState:UIControlStateNormal];
    [okBtn addTarget:self action:@selector(OnOKClick:) forControlEvents:UIControlEventTouchDown];
    [childPopUp addSubview:okBtn];
    
}

-(IBAction)OnOKClick :(id) sender{
    
    [_click_delegate okClicked];
    
}

-(void) show : (UIViewController *) parent{
    
}

-(void) hide{
    
    [self removeFromSuperview];
    
}

- (void)bounce1AnimationStopped {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:.2];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(bounce2AnimationStopped)];
    self.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.9, 0.9);
    [UIView commitAnimations];
}

- (void)bounce2AnimationStopped {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:.2];
    self.transform = CGAffineTransformIdentity;
    [UIView commitAnimations];
}


-(void) setBorderOnly:(UIView *) theView withBGColor:(UIColor *) color withCornerRadius :(float) radius andBorderWidth :(float) borderWidth andBorderColor :(UIColor *) bgColor WithAlpha:(float) curAlpha
{
    theView.layer.borderWidth = borderWidth;
    theView.layer.cornerRadius = radius;
    theView.layer.borderColor = [color CGColor];
    UIColor *c = [color colorWithAlphaComponent:curAlpha];
    theView.layer.backgroundColor = 1;
}

@end

I have a sample interface like this.

Custom PopUp IOS

Now the ViewController.m



#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController{

    CustomPopUp *mPopUp;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //create delegate    
    mPopUp = [CustomPopUp new];
    [mPopUp initAlertwithParent:self withDelegate:self];
    
    
}

-(void) okClicked{

    [mPopUp hide];
    
}

-(void) cancelClicked{
    NSLog(@"Cancel");
}

-(IBAction)showAlert :(id)sender{
    [mPopUp show];
}

-(IBAction)dummyClick :(id)sender{
    
    NSLog(@"Click Dummy");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end

MAKE SURE YOU HOOK UP THE BUTTONS TO THEIR CORRESPONDING FUNCTIONS.

You can download the complete source code from here.

StoryBoards in iOS – A Simple Example

Hey everyone,

Today we will see how we can use storyboards in an application.

First we will Create a sample project named “StoryBoardDemo”

StoryBoards in iOS, iPhone ,iPad, Apple

StoryBoards in iOS, iPhone ,iPad, Apple

Now we will Add the Navigation Controller
For that Go To Menu -> Editor >Embed In -> NavigationController

StoryBoards in iOS, iPhone ,iPad, Apple

StoryBoards in iOS, iPhone ,iPad, Apple

Now Double Click on the Title Bar and Add the title “Companies”

StoryBoards in iOS, iPhone ,iPad, Apple

Now Drag a table View on to the ViewController.
StoryBoards in iOS, iPhone ,iPad, Apple

Now we will add a prototype cell (a row) in the TableView

Search and Drag a “TableView Cell” inside the TableView.

StoryBoards in iOS, iPhone ,iPad, Apple

Now Select the TableView Prototype Cell and Go to the Attributes Inspector.

Select “Style = Basic”
Identifier = “Company_cell” // This is for referencing each row inside the code.

Now a new Label will appear inside the Prototype Cell.

StoryBoards in iOS, iPhone ,iPad, Apple

Make sure you link “delegate” and “datasource” to the view controller.
Otherwise data will not appear in the tableview.
For that Control Click on the tableView and Drag to the ViewController in the TreeView on
the left.

OK Now we will add another ViewController and add a connection between ViewControllers.

Right Click on the Project Name -> Add New Files > Cocoa touch
[Please UNTICK the checkbox to create the XIB file]

I said to UNTICK the creation of XIB file because we are here to study How STORYBOARD works right?

StoryBoards in iOS, iPhone ,iPad, Apple

So we will add new controller to the storyboard as follows.
Click on the Main.StoryBoard. Go to the Controls section and Search for ViewController and Drag to the storyboard and add a label to it.
You may customise the label you want.

StoryBoards in iOS, iPhone ,iPad, Apple

StoryBoards in iOS, iPhone ,iPad, Apple

Now Do exactly the same step.

Ctrl + Click on the TableView Row(prototype Cell) in the Companies-List ViewController and Drag to DetailsViewController.

Now a window will popup , From that under the “Select Sugue” section click “show”.
Here what we have done is we are telling the controller that when we click on the Tableview Row it should navigate to DetailView Controller.

Next Step Ctrl Click on the Bridge between the ComapniesViewController and DetailViewController, then Go to the attributes inspector on the right.
Give a name for the bridge.

StoryBoards in iOS, iPhone ,iPad, Apple

Now we will go to code

CompaniesViewController.h.

Add the tableview delegates, so that we can get the event on the click of the tableview.

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) IBOutlet UITableView *_tableView;

@end

CompaniesViewController.m

#import "CompaniesViewController.h"
#import "DetailsViewController.h"

@interface ViewController ()

@end

@implementation ViewController{
    NSArray *_companies;
}

@synthesize _tableView;

- (void)viewDidLoad {
    [super viewDidLoad];
    
      _companies = [NSArray arrayWithObjects:@"Apple", @"Google", @"Sony", @"Samsung", @"HTC", nil];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_companies count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"RecipeCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }
    
    cell.textLabel.text = [_companies objectAtIndex:indexPath.row];
    return cell;
}

// THIS IS THE FUNCTION THAT GETS CALLED WHEN A LINK BETWEEN
// VIEWCONTROLLERS IS ADDED IN THE STORYBOARD.

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"ShowCompanyDetail"]) {  // This should be the same id as the bridge between controllers.
        NSIndexPath *indexPath = [self._tableView indexPathForSelectedRow];
        DetailsViewController *destViewController = segue.destinationViewController;
        destViewController._companyName = [_companies objectAtIndex:indexPath.row];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end

In the DetailsViewController we will add two variables
one for the Label holding the value and the value itself

Make sure you link the label to the variable

DetailsViewController.h

#import <UIKit/UIKit.h>

@interface DetailsViewController : UIViewController

@property (nonatomic, strong) IBOutlet UILabel *_companyLabel;
@property (nonatomic, strong) NSString *_companyName;



@end

DetailsViewController.m


#import "DetailsViewController.h"

@interface DetailsViewController ()

@end

@implementation DetailsViewController

@synthesize _companyLabel;
@synthesize _companyName;

- (void)viewDidLoad {
    [super viewDidLoad];
    // we set the value passed from the companies view controller to the label
// in the Detailview controller.
    
    _companyLabel.text = _companyName;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

You can download the complete source code from here.

Localhost for Android Emulator and iPhone Simulator.

If you are trying to access a file (PHP or java) residing in your server in your own machine, then
you have to use a specific IP to access it. If it is public, then use the other System’s IP

1. If it is localhost, In Android you use it as

10.0.2.2

The localhost refers to the device on which the code is running, in this case the emulator.

If you want to refer to the computer which is running the Android simulator, use the IP address 10.0.2.2 instead. You can read more from here.

2. If you are trying to access from iOS Simulator use can use

http://localhost:8000/your_path

The iOS Simulator uses the host machine network so you should be able to just use localhost or your machines IP address, whichever IP your web service is listening on.

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.

Common.h

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

@end

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

@end

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>
{
    
}
@end

Now in the implementation class

ViewController.m

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

@interface ViewController ()

@end

@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]]){
            k--;
        }else{
            [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];
        imageView.image=image1;
        NSLog(@"Completed...");
    }
    
}

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:)
                                       forControlEvents:UIControlEventTouchDown];
        [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];
        y+=answerLabel.frame.size.height;
        
        [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.


-(IBAction)answerSelected:(id)sender
{
    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

iPhone

Yes,
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.

Motorola

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
http://www.telegraph.co.uk/technology/apple/9902864/Budget-iPhone-5-to-launch-soon.html

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

http://news.cnet.com/8301-13579_3-57570715-37/iphone-mini-launch-this-summer-makes-sense-analyst-says/

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.

http://www.bbc.co.uk/news/business-20856199

How to find your Google Plus ID

This is so simple

1. Go to your Google + account (https://plus.google.com/).

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:

https://plus.google.com/104653270154306099169/posts

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

104653270154306099169/

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.

iPhone

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..

http://online.wsj.com/article/SB10001424052702303360504577407610487811698.html?mod=googlenews_wsj

How to Play Audio using Corona SDK ?

Hi,

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 = audio.play( 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.