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

Download an image with ProgressBar in iOS

Hi all,

Today I will show you how you can download an image showing complete progress.

Make sure that you have an interface like the below image.

Download Image IOS Progress

You should link all the interface views with the corresponding variables in ViewController.h

ViewController.h


#import <uikit /UIKit.h>

@interface ViewController : UIViewController <nsurlconnectiondatadelegate>

@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (nonatomic, weak) IBOutlet UIButton   *btn_download;
@property (nonatomic, weak) IBOutlet UILabel   *lbl_download;

@end


ViewController.m



#import "ViewController.h"

@interface ViewController ()

@property (strong, nonatomic) NSURLConnection *connectionManager;
@property (strong, nonatomic) NSMutableData *downloadedMutableData;
@property (strong, nonatomic) NSURLResponse *urlResponse;

@end

@implementation ViewController{
    
#define IMAGE_URL @"http://img1.wikia.nocookie.net/__cb20111229061816/lego/images/b/b8/Ws-space-apple-logo.jpg"
}

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

-(IBAction)downloadImage :(id)sender{
    
    self.btn_download.enabled = NO;
    self.downloadedMutableData = [[NSMutableData alloc] init];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:IMAGE_URL]
                                                cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                            timeoutInterval:60.0];
    self.connectionManager = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
    
}

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

#pragma mark - Delegate Methods
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"%lld", response.expectedContentLength);
    self.urlResponse = response;
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.downloadedMutableData appendData:data];
    self.progressView.progress = ((100.0/self.urlResponse.expectedContentLength)*self.downloadedMutableData.length)/100;
    
    float per = ((100.0/self.urlResponse.expectedContentLength)*self.downloadedMutableData.length);
    self.lbl_download.text = [NSString stringWithFormat:@"%0.f%%", per];
    
    if (self.progressView.progress == 1) {
        self.progressView.hidden = YES;
        self.btn_download.enabled = YES;
    } else {
        self.progressView.hidden = NO;
    }
    
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    self.imageView.image = [UIImage imageWithData:self.downloadedMutableData];
    self.lbl_download.text = @"Download Complete";
}

@end

You can download the complete source code from here.

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.

NSURLConnection – A Simple example – Upload image to server using POST method.

Make sure you setup the server and have gone through this post before reading this article.

You can read more about NSURLConnection Class from here.

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/index.html#//apple_ref/occ/instm/NSURLConnection/

Here In this article I am going to select an image from the gallery and upload to a server using

1. Synchronous method
2. Asynchronous method – different ways.

First you have to make an interface like the below screenshot.
5 buttons, 1 Imageview and a label.
Make sure you hook all the controls to their respective labels and corresponding functions.

Upload Image To server using NSURLConnection

Upload Image To server using NSURLConnection

Now to the code.

ViewController.h


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UINavigationControllerDelegate,
UIImagePickerControllerDelegate, NSURLConnectionDelegate>{

    IBOutlet UILabel *response;
    NSMutableData *_responseData;
    
}


@property (strong, nonatomic) IBOutlet UIImageView* imageView;

- (IBAction) pickImage:(id)sender;


@end

ViewController.m


#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
{
    NSData *pngData;
    NSData *syncResData;
    NSMutableURLRequest *request;
    UIActivityIndicatorView *indicator;
    
    #define URL            @"http://localhost/UploadImage/Upload_Image.php"  // change this URL
    #define NO_CONNECTION  @"No Connection"
    #define NO_IMAGE      @"NO IMAGE SELECTED"
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    pngData = nil;
    [self initPB];
}

- (IBAction) pickImage:(id)sender{
    
    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    pickerController.delegate = self;
    [self presentViewController:pickerController animated:YES completion:nil];
}

#pragma mark -
#pragma mark UIImagePickerControllerDelegate

- (void) imagePickerController:(UIImagePickerController *)picker
         didFinishPickingImage:(UIImage *)image
                   editingInfo:(NSDictionary *)editingInfo
{
    self.imageView.image = image;
    pngData = UIImagePNGRepresentation(image);
    [self dismissModalViewControllerAnimated:YES];
}

-(BOOL) setParams{
    
    if(pngData != nil){
        
        [indicator startAnimating];
        
        request = [NSMutableURLRequest new];
        request.timeoutInterval = 20.0;
        [request setURL:[NSURL URLWithString:URL]];
        [request setHTTPMethod:@"POST"];
        
        NSString *boundary = @"---------------------------14737809831466499882746641449";
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
        [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
        [request setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
        [request setValue:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/536.26.14 (KHTML, like Gecko) Version/6.0.1 Safari/536.26.14" forHTTPHeaderField:@"User-Agent"];
        
        NSMutableData *body = [NSMutableData data];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploaded_file\"; filename=\"%@.png\"\r\n", @"Uploaded_file"] dataUsingEncoding:NSUTF8StringEncoding]];
        
        [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        
        [body appendData:[NSData dataWithData:pngData]];
        
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        
        
        [request setHTTPBody:body];
        [request addValue:[NSString stringWithFormat:@"%d", [body length]] forHTTPHeaderField:@"Content-Length"];
        
        return TRUE;
        
    }else{
        
        response.text = NO_IMAGE;
     
        return FALSE;
    }
}

- (IBAction) uploadImageSync:(id)sender
{
    
    if( [self setParams]){
        
        NSError *error = nil;
        NSURLResponse *responseStr = nil;
        syncResData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseStr error:&error];
        NSString *returnString = [[NSString alloc] initWithData:syncResData encoding:NSUTF8StringEncoding];
        
        NSLog(@"ERROR %@", error);
        NSLog(@"RES %@", responseStr);
        
        NSLog(@"%@", returnString);
        
        if(error == nil){
            response.text = returnString;
        }
    
        [indicator stopAnimating];
    
    }
    
}

- (IBAction) uploadImageAsync1:(id)sender
{

     if( [self setParams]){
    
        NSOperationQueue *queue = [[NSOperationQueue alloc]init];
        
        // Loads the data for a URL request and executes a handler block on an operation queue when the request completes or fails.
        [NSURLConnection sendAsynchronousRequest:request
                                           queue:queue
                               completionHandler:^(NSURLResponse *urlResponse, NSData *data, NSError *error){
                                   NSLog(@"Completed");
                                   
                                   response.text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                   
                                   [indicator stopAnimating];
                                   [UIApplication sharedApplication].networkActivityIndicatorVisible = FALSE;
                                   
                                   if (error) {
                                       NSLog(@"error:%@", error.localizedDescription);
                                   }
                                  
                               }];
     }
    

}

- (IBAction) uploadImageAsync2:(id)sender{
    
     if( [self setParams]){
    
         // Returns an initialized URL connection and begins to load the data for the URL request.
         if([[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]){
         
         };
         
     }
    
}

- (IBAction) uploadImageAsync3:(id)sender{
    
    if( [self setParams]){
        
       //Creates and returns an initialized URL connection and begins to load the data for the URL request.
        
        if([NSURLConnection connectionWithRequest:request delegate:self]){
            
        };
    }
    
}

-(void) initPB{
    indicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    indicator.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width)/2, ([UIScreen mainScreen].bounds.size.height)/2 , 40.0, 40.0);
    indicator.center = self.view.center;
    [self.view addSubview:indicator];
    [indicator bringSubviewToFront:self.view];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = TRUE;
}

#pragma mark NSURLConnection Delegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // A response has been received, this is where we initialize the instance var you created
    // so that we can append data to it in the didReceiveData method
    // Furthermore, this method is called each time there is a redirect so reinitializing it
    // also serves to clear it
    _responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to the instance variable you declared
    [_responseData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse*)cachedResponse {
    // Return nil to indicate not necessary to store a cached response for this connection
    return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // The request is complete and data has been received
    // You can parse the stuff in your instance variable now
    
    
    response.text = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
    NSLog(@"_responseData %@", response.text);
    
    [indicator stopAnimating];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = FALSE;
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // The request has failed for some reason!
    // Check the error var
    
    NSLog(@"didFailWithError %@", error);
    
}


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

@end

Now we go to the server side.

Please note the server file path in the code.
You must create a directory named “uploads” in the server before running the application.
Also Make sure that your server is running before you execute.

Refer the below Screenshot.

Upload Image To server using NSURLConnection

<?php
$target_path1 = "uploads/";

/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path1 = $target_path1 . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1)) {
    echo "The file ".  basename( $_FILES['uploaded_file']['name']).
    " has been uploaded to ".$target_path1;;
} else{
    echo "There was an error uploading the file, please try again!";
    echo "filename: " .  basename( $_FILES['uploaded_file']['name']);
    echo "target_path: " .$target_path1;
}
?>

You can download the complete source code from here.

Upload Image To server using NSURLConnection

Select an image from Gallery and show it in an ImageView in ios.

Hey all,

This is a simple post showing how you can open the “Gallery” or “Photos” application in iOS.

The Sample UI should look like this.

Select image from Gallery in ios

Screenshot selecting image from the Gallery.

Select image from gallery in ios

Now to the code.

ViewController.m

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UINavigationControllerDelegate,
UIImagePickerControllerDelegate>


@property (strong, nonatomic) IBOutlet UIImageView* imageView;

- (IBAction) pickImage:(id)sender;


@end

ViewController.m


#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

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

- (IBAction) pickImage:(id)sender{
    
    UIImagePickerController *pickerController = [[UIImagePickerController alloc]
                                                 init];
    pickerController.delegate = self;
    [self presentViewController:pickerController animated:YES completion:nil];
}

#pragma mark -
#pragma mark UIImagePickerControllerDelegate

- (void) imagePickerController:(UIImagePickerController *)picker
         didFinishPickingImage:(UIImage *)image
                   editingInfo:(NSDictionary *)editingInfo
{
    self.imageView.image = image;
    [self dismissModalViewControllerAnimated:YES];
}


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

@end

We add “UINavigationControllerDelegate,UIImagePickerControllerDelegate” to get the events after selecting the image from
the Gallery.

The below function is called after selecting image from Gallery

- (void) imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo

You can download the complete source code from here.

Send Data to server in iOS using POST OR GET – A Simple Example

First Make sure you have this kind of layout and you have linked all the views to their respective variables.

For server side I am using XAMPP for Localhost for now and My php file will be residing in Applications ▸ XAMPP ▸ xamppfiles ▸ htdocs

You can download “XAMPP For Mac” from this link.

When copying this code, make changes according to your server.

iOS Server connection using POST or GET
So I will go directly to the code.

ViewController.h


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<NSURLConnectionDelegate>
{
    IBOutlet UITextField *username, *passsword;
    IBOutlet UILabel *serverResponse;
}

@end

ViewController.m


#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController{
    
    NSMutableData *mutableData;
    
    #define URL            @"http://localhost/test.php"  // change this URL
    #define NO_CONNECTION  @"No Connection"
    #define NO_VALUES      @"Please enter parameter values"
   
}

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

-(IBAction)sendDataUsingPost:(id)sender{
    
    [self sendDataToServer :@"POST"];
   
}

-(IBAction)sendDataUsingGet:(id)sender{
    
    [self sendDataToServer : @"GET"];
}

-(void) sendDataToServer : (NSString *) method{
    
    NSString *usrname  = username.text;
    NSString *pass = passsword.text;
    
    if(usrname.length > 0 && pass.length > 0){
        
        serverResponse.text = @"Getting response from server...";
        
        NSURL *url = nil;
        NSMutableURLRequest *request = nil;
        
        // Only Difference between POST and GET is only in the way they send parameters
        
        if([method isEqualToString:@"GET"]){
            
            NSString *getURL = [NSString stringWithFormat:@"%@?username=%@&password=%@", URL, usrname, pass ];
            url = [NSURL URLWithString: getURL];
            request = [NSMutableURLRequest requestWithURL:url];
            
        }else{  // POST
            
            NSString *parameter = [NSString stringWithFormat:@"username=%@&password=%@",usrname, pass ];
            NSData *parameterData = [parameter dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
;
            url = [NSURL URLWithString: URL];
            request = [NSMutableURLRequest requestWithURL:url];
            [request setHTTPBody:parameterData];
        
        }
        
        [request setHTTPMethod:method];
        [request addValue: @"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
       
        NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
        
        if( connection )
        {
            
            mutableData = [NSMutableData new];
            
        }else{
            
            serverResponse.text = NO_CONNECTION;
            
        }
        
    }else{
        
        serverResponse.text = NO_VALUES;
        
    }
    
}

#pragma mark NSURLConnection delegates

-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response
{
    [mutableData setLength:0];
}

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [mutableData appendData:data];
}

-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    serverResponse.text = NO_CONNECTION;
    return;
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *responseStringWithEncoded = [[NSString alloc] initWithData: mutableData encoding:NSUTF8StringEncoding];
    //NSLog(@"Response from Server : %@", responseStringWithEncoded);
    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[responseStringWithEncoded dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    serverResponse.attributedText = attrStr;
}

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

@end


Here is the server side PHP code that can handle both POST and GET Requests.
Since you are getting the values, You can modify this code to say check with the database and
send appropriate result.

Here I am just sending back the values send from the Client Side (From iPhone or any other device)

<?php

	echo" Response From Server Side";

	echo "Username : " .$_REQUEST['username'];
	echo "Password : ".$_REQUEST['password'];
	
        // Do any database operations here...
?>

iOS Server Connection using POST and GET

You can download the complete source code from here.

What are static variables? Why it is used? What is it’s use? – A Common Interview Question.

The static keyword is used in java mainly for memory management. We may apply static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.

The static can be:

  • variable (also known as class variable)
  • method (also known as class method)
  • block
  • nested class
  • Static variable

  • If you declare any variable as static, it is known static variable.
  • The static variable can be used to refer the common property of all objects (that is not unique for each object)
  • The static variable gets memory only once in class area at the time of class loading.
  • For eg:

    public class Test {
    	public static String st_var = "I'm a static variable";
    }
    

    We can use this in another java class like below

    public class Application {
    	
    	public static void main(String[] args) {
    		System.out.println(Test.st_var); // call using Class name itself.
    	}
    
    }
    

    One common use of static is to create a constant value that’s attached to a class. The only change we need to make to the above example is to add the keyword final in there, to make ‘st_var’ a constant

    Another classic use of static is to keep count of how many objects are created from a given class. Since Memory is allocated only once for a static variable, If you create any number of objects ,then all objects will have only one common static variable. In this way we can count the number of objects created by incrementing the static variable inside that class

    If you make it Final, then it is unchangable after initial value.

    static method

  • If you apply static keyword with any method, it is known as static method
  • A static method belongs to the class rather than object of a class.
  • A static method can be invoked without the need for creating an instance of a class.
  • static method can access static data member and can change the value of it.
  • For Example

    Class Test{
     static void change(){  
         st_var = "CHANGED";  
     }  
     }
     and call Like this 
     
     Test.change(); // no need of object creation
     
    

    Restrictions for static method

    There are two main restrictions for the static method. They are:

  • The static method can not use non static data member or call non-static method directly.
  • this and super cannot be used in static context.
  • For Example

    class A{  
     int num=50;//non static  
       
     public static void main(String args[]){  
      System.out.println(num);  
     }  
    }  
    

    The output of above program will be a Compile Time Error.

    Simple way to Animating Layout Changes in Android.

    A layout animation is a pre-loaded animation that the system runs each time you make a change to the layout configuration. All you need to do is set an attribute in the layout to tell the Android system to animate these layout changes, and system-default animations are carried out for you.

      Create the Layout

    In your activity’s layout XML file, set the android:animateLayoutChanges attribute to true for the layout that you want to enable animations for. For instance:

    <LinearLayout android:id="@+id/container"
        android:animateLayoutChanges="true"
        ...
    />
    
      Add, Update, or Remove Items from the Layout

    Now, all you need to do is add, remove, or update items in the layout and the items are animated automatically:

    private ViewGroup mContainerView;
    ...
    private void addItem() {
        View newView;
        ...
        mContainerView.addView(newView, 0);
    }
    
    

    Here is the complete sample layout file.

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:id="@+id/container"
        android:orientation="vertical"
        android:layout_height="match_parent"
        tools:context=".MainActivity" 
        android:animateLayoutChanges="true">
    
        <Button
            android:id="@+id/buttonAdd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Add Views" />
    
         <Button
            android:id="@+id/buttonRemove"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Remove Views" />
         
    </LinearLayout>
    

    The MainActivity file.

    package com.coderzheaven.demo1;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.LinearLayout;
    
    public class MainActivity extends Activity {
    
    	LinearLayout mContainerView;
    	int id = 0;
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    
    		mContainerView = (LinearLayout) findViewById(R.id.container);
    		Button click = (Button) findViewById(R.id.buttonAdd);
    		click.setOnClickListener(new OnClickListener() {
    
    			@Override
    			public void onClick(View arg0) {
    				addView();
    			}
    		});
    		Button remove = (Button) findViewById(R.id.buttonRemove);
    		remove.setOnClickListener(new OnClickListener() {
    
    			@Override
    			public void onClick(View arg0) {
    				removeView();
    			}
    		});
    	}
    
    	void addView() {
    		Button b = new Button(this);
    		b.setId(id++);
    		b.setText("Button " + id);
    		mContainerView.addView(b, 0);
    	}
    
    	void removeView() {
    
    		View v = (View) findViewById(id - 1);
    		if (v != null) {
    			id--;
    			v.setVisibility(View.GONE);
    		}
    	}
    }
    
    

    Just try with a sample layout and see the magic.

    Check if Connected to Internet & if isConnected to Wifi in Android.

    This sample code checks whether the android device is connected to Internet and
    if it is connected to internet, it is connected to Wifi or Not?

    package com.coderzheaven.demo1;
    
    import android.app.Activity;
    import android.content.Context;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.os.Bundle;
    
    public class MainActivity extends Activity {
    
    	NetworkInfo activeNetwork;
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    
    		if (connectedToInternet())
    			System.out.println("Connected to Internet.");
    		else
    			System.out.println("Not Connected to internet");
    
    		if (isWifi())
    			System.out.println("Connected to Wifi.");
    		else
    			System.out.println("Not Connected to Wifi");
    	}
    
    	Boolean connectedToInternet() {
    		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    
    		activeNetwork = cm.getActiveNetworkInfo();
    		return (activeNetwork != null && activeNetwork
    				.isConnectedOrConnecting());
    
    	}
    
    	Boolean isWifi() {
    		return (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI);
    	}
    }
    

    MAKE SURE YOU ADD BELOW PERMISSION TO THE ANDROID MANIFEST

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    

    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.

    Open Camera, Take Photo, Save it, Load it – iOS Sample code

    This example shows how to Open Camera, Take Photo, Save it, Load it in iOS.

    Camera Functions in IOS


    Before this make sure that you have two buttons and one imageview in the Interface (image above) and link them to appropriate actions
    and variables

    ViewController.h”

    
    #import <UIKit/UIKit.h>
    
    @interface ViewController : UIViewController <UIImagePickerControllerDelegate>
    {
        UIImagePickerController *imagePicker;
        IBOutlet UIImageView *imageView;
    }
    
    - (IBAction)showCamera:(id)sender;
    - (IBAction)loadImage:(id)sender;
    
    @end
    
    
    

    ViewController.m

    
    
    #import "ViewController.h"
    
    @interface ViewController ()
    {
        #define FILE_EXTENSION    @".png"
        #define IMAGE_NAME        @"CameraImage"
    }
    @end
    
    @implementation ViewController
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            imagePicker = [[UIImagePickerController alloc]init];
            imagePicker.delegate = self;
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePicker.allowsEditing = YES;
            
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Camera Unavailable"
                                                           message:@"Unable to find a camera on your device."
                                                          delegate:nil
                                                 cancelButtonTitle:@"OK"
                                                 otherButtonTitles:nil, nil];
            [alert show];
            alert = nil;
        }
    }
    
    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
    }
    
    - (IBAction)showCamera:(id)sender {
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
    
    +(NSString *)documentsPath:(NSString *)fileName {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:fileName];
        NSLog(@"%@", fullPath);
        
        return fullPath;
    }
    
    -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
    {
        NSString *fileSavePath = [ViewController documentsPath:IMAGE_NAME];
        fileSavePath = [fileSavePath stringByAppendingString:FILE_EXTENSION];
        
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        if (image == nil) {
            image = [info objectForKey:UIImagePickerControllerOriginalImage];
        }
        
        //This checks to see if the image was edited, if it was it saves the edited version as a .png
        if ([info objectForKey:UIImagePickerControllerEditedImage]) {
            //save the edited image
            NSData *imgPngData = UIImagePNGRepresentation([info objectForKey:UIImagePickerControllerEditedImage]);
            [imgPngData writeToFile:fileSavePath atomically:YES];
            
            
        }else{
            //save the original image
            NSData *imgPngData = UIImagePNGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage]);
            [imgPngData writeToFile:fileSavePath atomically:YES];
            
        }
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }
    
    -(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    - (IBAction)loadImage:(id)sender{
        NSString *path = [NSString stringWithFormat:@"%@%@",[ViewController documentsPath:IMAGE_NAME], FILE_EXTENSION];
        NSData *imgData = [NSData dataWithContentsOfFile:path];
        UIImage *thumbNail = [[UIImage alloc] initWithData:imgData];
        imageView.image = thumbNail;
    }
    
    @end
    
    

    Customizing UITableView using “Prototype Cells” in iOS.

    Hi all,

    In today’s tutorial we will study how we can customize a UITableView using “Prototype Cells” in iOS which was introduced
    in XCode 5.0.

    First Create a new Project and Name it “CustomTBLView”.

    Now you will get the Main.storyBoard file with other ViewController and Delegate Files.

    Open Main.storyBoard and “Drag” a TableView on to it.

    Now Drag a “UITableViewCell” on to it. This is the Prototype Cell.

    Now our “Main.storyBoard” looks like this.

    Prototype Cells in iOS

    Now select the tableView cell from the Hierarchy and Go to the “Attributes Inspector” on the right side.

    Select Style = ” Basic ”
    Indentifier = “list_item_cell”

    Now you will see that a “Label” will appear in the cell.
    Click on the label and go to “Attributes Inspector” and give tag as “100”.

    Prototype Cells in iOS

    Here “list_item_cell” is the identifier for each prototype cell.
    We will use this identifier to get the cell and populate the items.

    [ Make sure you like the "delegate" and "datasource" to the ViewController, otherwise no data will be loaded in
    the tableview ]

    Our work in the Interface Builder is over.

    Now Lets do the coding part

    Go to the ViewController.h and paste the delegates and the array

    ViewController.h

    #import <UIKit/UIKit.h>
    
    @interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
    {
        
    }
    
    @property (strong, nonatomic) NSMutableArray *_tblData;
    
    @end
    
    

    Now go to ViewController.m and synthesize the array.

    These are the delegate methods

    - (NSInteger)numberOfSectionsInTableView: (UITableView *)tableView {
    }
    - (NSInteger)tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger)section {
    }
    - (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
    }
    

    Now your ViewController.m will look like this.

    
    
    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    @synthesize _tblData;
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        if (!_tblData) {
            _tblData = [[NSMutableArray alloc] initWithObjects:@"iPhone", @"Android", @"Windows", @"Apple", @"Google", @"Microsoft", nil];
        }
    
    }
    
    - (NSInteger)numberOfSectionsInTableView: (UITableView *)tableView {
        return 1;
    }
    
    - (NSInteger)tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger)section {
        
        return [_tblData count];
    
    }
    
    - (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
       
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"list_item_cell"];
        UILabel *lblName = (UILabel *)[cell viewWithTag:100];
        [lblName setText:[_tblData objectAtIndex:[indexPath row]]]; return cell;
    
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
    }
    
    @end
    
    

    OK Done. Run the project.

    Prototype Cells in iOS

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

    Building Custom Components in Android.

    Hi everyone,

    In this tutorial we will be building a Custom TextView.
    ie. this TextView will be extending the inBuil TextView and have its own custom attributes
    along with the default attributes in a TextView in Android.

    So we will start.

    We will be making a custom textview and presenting to the UI using

    1. XML
    2. Java Code

    1. Using Java Code

    Create a class named CustomTV and extend TextView.

    CustomTV.java

    package com.coderzheaven.customcomponent;
    
    import android.content.Context;
    import android.content.res.TypedArray;
    import android.graphics.Color;
    import android.util.AttributeSet;
    import android.widget.TextView;
    import com.coderzheaven.customcomponent.R;
    
    public class CustomTV extends TextView {
    
    	public CustomTV(Context context) {
    		super(context);
    	}
    
    	public CustomTV(Context context, AttributeSet attrs) {
    	    super(context, attrs);
    	}
    
    	public CustomTV(Context context, AttributeSet attrs, int defStyle) {
    	    super(context, attrs, defStyle);
    	    
    	}
    	   
    }
    

    Now we go to the MainActivity and place the Custom textview using java code.

    package com.coderzheaven.customcomponent;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.widget.LinearLayout;
    
    public class MainActivity extends Activity {
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    
    		LinearLayout lin = (LinearLayout) findViewById(R.id.lin);
    
    		CustomTV tv = new CustomTV(this);
    		tv.setText("I am a custom TextView from java code With Custom Attributes");
    		tv.setPadding(20, 20, 20, 20);
    		lin.addView(tv);
    
    	}
    
    }
    

    activity_main.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"   
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/lin"
        android:orientation="vertical"
        tools:context=".MainActivity" >
      
    </LinearLayout>
    

    1. Using XML

    There is no change in the java code above. Instead we will be adding one more TextView in the
    activity_main.xml which is our custom one.

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/lin"
        android:orientation="vertical"
        tools:context=".MainActivity" >
    
        <com.coderzheaven.customcomponent.CustomTV
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:text="I am Custom TextView in the XML with Custom Attributes" />
    
    </LinearLayout>
    

    NOW WE WILL SEE HOW CAN APPLY OUR OWN ATTRIBUTES TO OUR CUSTOM TEXTVIEW.

    Let’s say my custom textview should have an attribute “my_color” to which I can apply my own color as string.
    [We know there is already a method for setting color in a TextView, but this is only for illustration purpose]

    Create an xml named “attrs.xml” inside res/values and copy this code into it.

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    
        <declare-styleable name="CustomTV">
            <attr name="my_color" format="string" />
        </declare-styleable>
    
    </resources>
    

    Now go to activity_main.xml and change xml code like this.
    Make sure to add your custom namespace [xmlns:custom="http://schemas.android.com/apk/res/com.coderzheaven.customcomponent"]

    activity_main.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:custom="http://schemas.android.com/apk/res/com.coderzheaven.customcomponent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/lin"
        android:orientation="vertical"
        tools:context=".MainActivity" >
    
        <com.coderzheaven.customcomponent.CustomTV
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            custom:my_color="#FF0000"  
            android:text="I am Custom TextView in the XML with Custom Attributes" />
    
    </LinearLayout>
    

    Now if you run, you can see your custom color to your custom TextView.

    Our CustomTV.java will change like this inorder to get the custom attributes and apply
    our own modifications.

    package com.coderzheaven.customcomponent;
    
    import android.content.Context;
    import android.content.res.TypedArray;
    import android.graphics.Color;
    import android.util.AttributeSet;
    import android.widget.TextView;
    import com.coderzheaven.customcomponent.R;
    
    public class CustomTV extends TextView {
    
    	public CustomTV(Context context) {
    		super(context);
    	}
    
    	public CustomTV(Context context, AttributeSet attrs) {
    		super(context, attrs);
    
    		TypedArray a = context.obtainStyledAttributes(attrs,
    				R.styleable.CustomTV);
    
    		final int N = a.getIndexCount();
    		for (int i = 0; i < N; ++i) {
    			int attr = a.getIndex(i);
    			switch (attr) {
    			case R.styleable.CustomTV_my_color:
    				String my_color = a.getString(attr);
    				setCustomColor(my_color);
    				break;
    			}
    		}
    		a.recycle();
    
    	}
    
    	public void setCustomColor(String color) {
    		this.setTextColor(Color.parseColor(color));
    	}
    
    	public CustomTV(Context context, AttributeSet attrs, int defStyle) {
    		super(context, attrs, defStyle);
    
    	}
    
    }
    
    

    Apply your custom attribute in Java code also.

       tv.setCustomColor("#00FF00");
    

    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.

    Xcode 6 crashes when validating or submitting app archive.

    Before somedays some people might have experienced this issue when you are trying to
    validate or while submitting, the Xcode just crashes.

    However its the problem with the XCode due to wrong programming practice or
    not a professional approach from Apple. Apple could have warned the user about what is wrong.

    There is a simple solution to this.

  • To check if you need to, you can go to the preferences -> accounts in XCode, Click “View details” of an account and
    attempt to refresh using the little button. Here, XCode will warn you that you need to accept new agreements in the
    Member Center before you can refresh.
  • if ther is any, then you have to go to the Member Center (https://developer.apple.com/devcenter/ios/index.action)
    and Accept all agreements.
  • Double click new provision profiles you downloaded to install them, and then XCode will never crash.

  • The problem is caused by XCode 6.0 does not handle provision profile migration properly.
    Developers should regenerate provision profiles for XCode 6+, but Xcode 6.0 fails to display this error message properly and crashes. (If you use XCode 6.1 Beta, it will display error messages for you, no crash.
    Then you will know that the problem is caused by “invalid”==”legacy” provision profile.)

    After that try again validating and submitting your app and it should Work successfully.

    Thanks for reading this post, if the above solution works, then please rate and comment below.

    Nexus 6 Came…

    Nexus 6

    Google Nexus 6

    Specifications

    GENERAL 2G Network GSM 850 / 900 / 1800 / 1900 – all models
      CDMA 800 / 1900 – XT1103 US model
    3G Network HSDPA 800 / 850 / 1700 / 1900 / 2100 / 900 – XT1100 Global model
      HSDPA 850 / 900 / 1700 / 1900 / 2100 – XT1103 US model
    4G Network LTE 700 / 800 / 900 / 1800 / 2100 / 2600 / 850 / 2500 – XT1100 Global model
      LTE 700 / 850 / 900 / 1800 / 1900 / 2100 / 2600 / 2500 – XT1103 US model
    SIM Nano-SIM
    Announced 2014, October
    Status Coming soon. Exp. release 2014, October
    BODY Dimensions 159.3 x 83 x 10.1 mm (6.27 x 3.27 x 0.40 in)
    Weight 184 g (6.49 oz)
    DISPLAY Type AMOLED capacitive touchscreen, 16M colors
    Size 1440 x 2560 pixels, 5.96 inches (~493 ppi pixel density)
    Multitouch Yes
    Protection Corning Gorilla Glass 3
    SOUND Alert types Vibration; MP3, WAV ringtones
    Loudspeaker Yes, with stereo speakers
    3.5mm jack Yes
    MEMORY Card slot No
    Internal 32/64 GB, 3 GB RAM
    DATA GPRS Yes
    EDGE Yes
    Speed DC-HSDPA, 42 Mbps; HSDPA, 21 Mbps; HSUPA, 5.76 Mbps; LTE, Cat6, 50 Mbps UL, 300 Mbps DL
    WLAN Wi-Fi 802.11 a/b/g/n/ac, dual-band, Wi-Fi Direct, DLNA, Wi-Fi hotspot
    Bluetooth v4.0, A2DP
    NFC Yes
    USB microUSB v2.0 (SlimPort), USB Host, USB On-the-go
    CAMERA Primary 13 MP, 4128 x 3096 pixels, autofocus, optical image stabilization, dual-LED flash
    Features Geo-tagging, touch focus, face detection, photo sphere, HDR, dual recording
    Video 2160p@30fps, optical stabilization
    Secondary 2 MP
    FEATURES OS Android OS, v5.0 (Lollipop)
    Chipset Qualcomm Snapdragon 805
    CPU Quad-core 2.7 GHz Krait 450
    GPU Adreno 420
    Sensors Accelerometer, gyro, proximity, compass, barometer
    Messaging SMS(threaded view), MMS, Email, Push Mail, IM
    Browser HTML5
    Radio No
    GPS Yes, with A-GPS, GLONASS
    Java Yes, via Java MIDP emulator
    Colors Midnight Blue, Cloud White
      – Wireless charging
    – Active noise cancellation with dedicated mic
    – MP4/H.264/H.263 player
    – MP3/WAV/eAAC+ player
    – Organizer
    – Photo/video editor
    – Document editor
    – Voice memo/dial/commands
    – Predictive text input
    BATTERY   Non-removable Li-Po 3220 mAh battery
    Stand-by Up to 330 h
    Talk time Up to 24 h

    How to change title and Subtitle text color and size of ActionBar in Android?

    Here is a simple example that shows how you can change title and subtitle textcolor and its size in Android

    Method 1
    ——–

    Changing the styles [For support Library]

    Go to Values/styles.xml copy this code to change the textcolor and actionbar background color.

    
    <style name="CustomActivityTheme" parent="@style/Theme.AppCompat.Light">
            <item name="android:actionBarStyle">@style/MyActionBar</item>
            <item name="actionBarStyle">@style/MyActionBar</item>
             <item name="android:windowActionBarOverlay">true</item>
            <!-- other activity and action bar styles here -->
    </style>
          <!-- style for the action bar backgrounds -->
    <style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar">
            <item name="android:background">@drawable/actionbar_background</item>
            <item name="background">@drawable/actionbar_background</item>
            <item name="android:titleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
            <item name="android:subtitleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
            <item name="titleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
            <item name="subtitleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
         </style>
    <style name="MyTheme.ActionBar.TitleTextStyle" parent="@android:style/TextAppearance">
            <item name="android:textColor">@color/color_title</item>
            <item name="android:textSize">12sp</item>
    </style>
    	  
    	  
    

    Note : For applying theme if you are not using the Support Library then change the AppCompat to Holo.

    i.e make the Below changes in the parent

    parent="@android:style/Theme.Holo.Light"
    

    AND

    parent="@android:style/Widget.Holo.Light.ActionBar"
    

    AND for title

    parent="@android:style/TextAppearance.Holo.Widget.ActionBar.Title"
    

    Now Apply this theme in the AndroidManifest.xml, either for the entire application or a particular activity.

    For example

    
     <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/CustomActivityTheme" >
            <activity
                android:name="com.example.actionbarcustomize.MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
     </application>
    	
    

    Make Sure you add the colors in the strings.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    
        <string name="app_name">ActionBarCustomize</string>
        <string name="hello_world">Hello world!</string>
        <string name="menu_settings">Settings</string>
    
        <drawable name="actionbar_background">#FF0000</drawable>
        <color name="color_title">#00FF00</color>
    	
    </resources>
    

    Method 2
    ———

    You can use a simple java code to so this.

    getActionBar().setTitle(Html.fromHtml("<font color='#ff0000'>ActionBartitle </font>"));
    

    Note : Change getActionBar() to getSupportActionBar() if you are using the support library for ActionBar.

    That’s all.. Now Run the application and see the changes.

    Android In App Purchased Demo V3.

    Hi all,

    This demo shows how to do in app purchase for managed products in Android using Version 3 in-app Billing API.

    Please Go through this before trying out this Demo

    http://developer.android.com/google/play/billing/index.html

    Android In App Purchase

    These are the important steps in to remember for doing in app purchase.

    1. You have to download the Google In App Billing Library from Google.

    For that you have to open the Android SDK Manager and Look for “Google Play Billing Library”.

    2. You have to make changes in the Android Manifest first.

    Add this permission.

         <!-- Permission for In App Purchase -->
        <uses-permission android:name="com.android.vending.BILLING" />
         

    The above permission will detect that your app contains “In App Purchases” in Google Play Store.

    3. Now add the .aidl file that you get while downloading the library from Google.

    [You can find this library in the Sample Project at the end of this post].

    4. Now let’s assume that we have done the coding part by giving a demo in_app item.

    5. You can test the application in two ways either using STATIC RESPONSES from Google Play

    OR real purchases with users but without using any money.

    STATIC TESTING :

    READ THIS LINK : http://developer.android.com/google/play/billing/billing_testing.html#billing-testing-static

    REAL TESTING – AFTER UPLOADING TO GOOGLE PLAY (IN ALPHA OR BETA MODE)

    READ THIS LINK : http://developer.android.com/google/play/billing/billing_testing.html#testing-purchases.

    NOTE : If you publish your application through Alpha or Beta mode, the users who are downloading from Google Play will not see it or get it. In that way Google ensures that it is not published before testing.

    For REAL TESTING AFTER UPLOADING TO GOOGLE PLAY you must be adding some users as Test Users who can test this app that you have
    You can add test users while you upload the apk with in app Billing in Alpha or Beta Mode.

    For adding test users you can see a link in the APK page of the particular app in Alpha or Beta Mode.[This is usually a Google community or Groups]

    For a user to be a Test account you have to go to Settings > Gmail accounts with testing access > add the Gmail account to test.

    This means that these users can buy this in app Item without loosing any money in alpha or Beta Mode.

    Important Note :

    In Google In App Billing V3, all purchases are managed that means you can even consume managed products.

    PRODUCTS ONCE CONSUMED WILL BE A AVAILABLE FOR PURCHASE AGAIN.

    THAT MEANS IF YOU PURCHASE A MANAGED PRODUCT AND IF THE USER CONSUMES IT, THEN IT WILL BE AGAIN AVAILABLE FOR PURCHASE.

    IF THE USER CONSUMES IT GOOGLE WILL REMOVE THAT PURCHASED ITEM FROM IT’S SEVER AND MARK IT AS ‘UN-OWNED’.

    SO WHEN YOU QUERY THE PURCHASED ITEMS YOU WILL NOT BE GETTING THE PURCHASED ITEM.

    SO IF YOU WANT THE USER TO PURCHASE THE ITEM ONLY ONCE AND AVAILABLE ALL THE TIME DON’T CONSUME IT

    THAT MEANS YOU HAVE TO COMMENT OUT THIS CODE FROM THE SAMPLE CODE PROVIDED.

       	mHelper.consumeAsync(purchase, mConsumeFinishedListener);
       

    That is you can directly write your code inside this if the purchase is sucessful

       if (purchase.getSku().equals(SKU_INAPPITEM)) {
       }
       

    OK Done.

    You can download the sample application from this link

    Download In App Billing Source Code

    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.