QR Scanner in iOS

QR Scanner in iOS is fairly easy to implement.

Make sure you have a layout like this.

Scanner in iOS

Drag an audio file beep.mp3 into your resources.

I have the ViewController.h file like this

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

@interface ViewController : UIViewController <AVCaptureMetadataOutputObjectsDelegate>
{
       IBOutlet UIView *viewPreview;
    __weak IBOutlet UILabel *lblQrCode;
}

@property (weak, nonatomic) IBOutlet UIButton *btnScan;

@end

and the ViewController.m file like this.


#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;

@end

@implementation ViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self checkLaunchOrientation];

    [self startReading:nil];
    
}

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

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscape;
}

-(void)checkLaunchOrientation {
    
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    UIDeviceOrientation interfaceOrientation = [[UIDevice currentDevice] orientation];
    
    if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft) {
        
        AVCaptureConnection *con = self.videoPreviewLayer.connection;
        con.videoOrientation = AVCaptureVideoOrientationLandscapeRight;
    }
    
    else if(interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        
        AVCaptureConnection *con = self.videoPreviewLayer.connection;
        con.videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
    }
    
}

- (BOOL)shouldAutorotate {
    return (UIDeviceOrientationIsLandscape([[UIDevice currentDevice] orientation]));
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    if([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) {
        AVCaptureConnection *con = self.videoPreviewLayer.connection;
        con.videoOrientation = AVCaptureVideoOrientationLandscapeRight;
    } else {
        AVCaptureConnection *con = self.videoPreviewLayer.connection;
        con.videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
    }
}

#pragma mark - Private method implementation

- (IBAction)startReading:(UIButton *)sender {
    NSError *error;
    
    // Get an instance of the AVCaptureDevice class to initialize a device object and provide the video
    // as the media type parameter.
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Get an instance of the AVCaptureDeviceInput class using the previous device object.
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    
    if (!input) {
        // If any error occurs, simply log the description of it and don't continue any more.
        NSLog(@"%@", [error localizedDescription]);
        return;
    }
    
    // Initialize the captureSession object.
    _captureSession = [[AVCaptureSession alloc] init];
    // Set the input device on the capture session.
    [_captureSession addInput:input];
    
    
    // Initialize a AVCaptureMetadataOutput object and set it as the output device to the capture session.
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    [_captureSession addOutput:captureMetadataOutput];
    
    // Create a new serial dispatch queue.
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
    
    // Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer.
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    
    AVCaptureConnection *con = self.videoPreviewLayer.connection;
    
    if([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) {
        con.videoOrientation = AVCaptureVideoOrientationLandscapeRight;
    } else {
        con.videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
    }
    
    [_videoPreviewLayer setFrame:viewPreview.layer.bounds];
    [viewPreview.layer addSublayer:_videoPreviewLayer];
    
    // Start video capture.
    [_captureSession startRunning];

}

-(void)stopReading{
    // Stop video capture and make the capture session object nil.
    [_captureSession stopRunning];
    _captureSession = nil;
    
    // Remove the video preview layer from the viewPreview view's layer.
    [_videoPreviewLayer removeFromSuperlayer];
    
    [self performSelector:@selector(backTapped:) withObject:nil afterDelay:0.1];
    
}

#pragma Audio Play
-(void)loadBeepSound{
    
    NSString *beepFilePath = [[NSBundle mainBundle] pathForResource:@"beep" ofType:@"mp3"];
    NSURL *beepURL = [NSURL URLWithString:beepFilePath];
    
    NSError *error;
    
    _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:beepURL error:&error];
    
    if (error) {
        
        NSLog(@"Could not play beep file.");
        NSLog(@"%@", [error localizedDescription]);
    }
    else{
        
        [_audioPlayer prepareToPlay];
    }
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate method implementation

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    
    // Check if the metadataObjects array is not nil and it contains at least one object.
    
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        // Get the metadata object.
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
            
            NSString *qrCode = [metadataObj stringValue];
            lblQrCode.text = [lblQrCode.text stringByAppendingString:qrCode];
                     
            // If the audio player is not nil, then play the sound effect.
            if (_audioPlayer) {
                [_audioPlayer play];
            }
        }
        [self loadBeepSound];
        [self performSelectorOnMainThread:@selector(stopReading) withObject:nil waitUntilDone:NO];
        
        self.btnScan.hidden = NO;
    }
    
}

- (IBAction)backTapped:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end

You can download the complete source code from here

What is the difference between “let” and “var” in swift programming language?

The: let keyword defines a constant:

let theAnswer = 43

The theAnswer cannot be changed afterwards.

The var defines an ordinary variable:

What is interesting:

The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once.

Another strange feature:

You can use almost any character you like for constant and variable names, including Unicode characters:

let 🐀 = “rat”

Google Maps in iOS – Search your location

Here is a simple tutorial that helps you to start with Google Maps for iOS.

Google Maps iOS

Make sure that you have a textbox and a button and a view just below them for placing the Google Map in your interface builder.
There is no control for adding Google Maps, the Map is added dynamically in the code.

Here is the Google Documentation to start with Google Maps.
https://developers.google.com/maps/documentation/ios/start

To start with Google Maps you need the following

The Google Maps API key (this key is used in the Code for initializing maps, Make sure that you API and your bundle identifier matches when you register for maps with Google, otherwise the map will not load.)

If you have downloaded the Google Maps SDK, then you have to integrate it in your project.

Follow the below steps.

Launch Xcode and either open an existing project, or create a new project.
If you’re new to iOS, create a Single View Application, and ensure that Use Automatic Reference Counting is on.
Drag the GoogleMaps.framework bundle to your project. When prompted, select Copy items if needed.
Right-click GoogleMaps.framework in your project, and select Show In Finder.
Drag the GoogleMaps.bundle from the Resources folder to your project. When prompted, ensure Copy items into destination group’s folder is not selected.
Select your project from the Project Navigator, and choose your application’s target.
Open the Build Phases tab, and within Link Binary with Libraries, add the following frameworks:
AVFoundation.framework
CoreData.framework
CoreLocation.framework
CoreText.framework
GLKit.framework
ImageIO.framework
libc++.dylib
libicucore.dylib
libz.dylib
OpenGLES.framework
QuartzCore.framework
SystemConfiguration.framework
Choose your project, rather than a specific target, and open the Build Settings tab.
In the Other Linker Flags section, add -ObjC. If these settings are not visible, change the filter in the Build Settings bar from Basic to All.
Finally, add your API key to your AppDelegate.
#import
Add the following to your application:didFinishLaunchingWithOptions: method, replacing API_KEY with your API key.

[GMSServices provideAPIKey:@”API_KEY”];

After that Clean and build your project.

Please don’t forget to add “-ObjC” in Other Linked Flags, otherwise it will result in an error.

Now Lets go to our Coding part.

AppDelegate.h

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

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end


AppDelegate.m

MAKE SURE YOU CHANGE THE API KEY WITH YOURS IN THE BELOW CODE.


#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    NSLog(@"my bundle id is: %@", [[NSBundle mainBundle] bundleIdentifier]);
    [GMSServices provideAPIKey:@"YOUR API KEY"];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end

This is your main view controller that contains the maps.
ViewController.h


#import <UIKit/UIKit.h>
#import "GetSearchData.h"
#import <GoogleMaps/GoogleMaps.h>
#import <CoreLocation/CoreLocation.h>

@interface ViewController : UIViewController<ServiceListener, GMSMapViewDelegate, CLLocationManagerDelegate>
{
      CLLocationManager *locationManager;
}
@property (weak, nonatomic) IBOutlet UITextField *searchTxt;
@property (weak, nonatomic) IBOutlet UIView *mapParentView;

- (IBAction)search:(id)sender;

@end

ViewController.m

#import "ViewController.h"

@interface ViewController (){
    GMSMapView *mapView_;
}

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 &&
        [CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse
        //[CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways
        ) {
        // Will open an confirm dialog to get user's approval
        [locationManager requestWhenInUseAuthorization];
        //[_locationManager requestAlwaysAuthorization];
    } else {
       
    }
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
    [locationManager startUpdatingLocation]; //Will update location immediately
}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError: %@", error);
    UIAlertView *errorAlert = [[UIAlertView alloc]
                               initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [errorAlert show];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}

// Wait for location callbacks
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    NSLog(@"%@", [locations lastObject]);
    
    CLLocation *currentLocation = [locations lastObject];
    
    [locationManager stopUpdatingLocation];
    
    [mapView_ clear];
    
    [mapView_ animateToLocation:CLLocationCoordinate2DMake(currentLocation.coordinate.latitude, currentLocation.coordinate.longitude)];
    
     [self setMarkerWithLatitiude:currentLocation.coordinate.latitude Longitude:currentLocation.coordinate.longitude andTitle:self.searchTxt.text];
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"didUpdateToLocation: %@", newLocation);
    CLLocation *currentLocation = newLocation;
    
    if (currentLocation != nil) {
        
        [mapView_ clear];
        
        [mapView_ animateToLocation:CLLocationCoordinate2DMake(currentLocation.coordinate.latitude, currentLocation.coordinate.longitude)];
        
        
        [self setMarkerWithLatitiude:currentLocation.coordinate.latitude Longitude:currentLocation.coordinate.longitude andTitle:self.searchTxt.text];
       
    }
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}

#pragma mark - mapview events
-(BOOL) mapView:(GMSMapView *)mapView didTapMarker:(GMSMarker *)marker{
    NSLog(@"%@", marker.description);
    //    show info window
    [mapView_ setSelectedMarker:marker];
    return YES;
}

- (void)viewDidAppear:(BOOL)animated{
    
    CLLocationCoordinate2D myLocation = mapView_.myLocation.coordinate;
    
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:myLocation.latitude
                                                            longitude:myLocation.longitude
                                                                 zoom:6];
    mapView_ = [GMSMapView mapWithFrame:CGRectMake(0, 0, self.mapParentView.frame.size.width, self.mapParentView.frame.size.height) camera:camera];
    mapView_.myLocationEnabled = YES;
    [self.mapParentView  addSubview:mapView_];
    
    [self setMarkerWithLatitiude:myLocation.latitude Longitude:myLocation.longitude andTitle:self.searchTxt.text];
    
    mapView_.delegate = self;
    
    self.mapParentView.backgroundColor = [UIColor whiteColor];
}


-(void) onSuccess :  (NSMutableArray *) jsonArray
{
    
    NSDictionary *results = [jsonArray valueForKey:@"results"];
    NSDictionary *geometry = [results valueForKey:@"geometry"];
    
    NSArray *location = [geometry valueForKey:@"location"];
    NSDictionary *vals = [location objectAtIndex:0];
    float lat = [[vals objectForKey:@"lat"] floatValue];
    float lng = [[vals objectForKey:@"lng"] floatValue];

    NSLog(@"Lat %@",[vals objectForKey:@"lat"]);
    NSLog(@"lng %@",[vals objectForKey:@"lng"]);
    
    [mapView_ animateToLocation:CLLocationCoordinate2DMake(lat, lng)];
    
    // Creates a marker in the center of the map.
    [self setMarkerWithLatitiude:lat Longitude:lng andTitle:self.searchTxt.text];
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    
}

-(void) setMarkerWithLatitiude : (float) lat Longitude : (float) lng andTitle : (NSString *) title
{
    GMSMarker *marker = [[GMSMarker alloc] init];
    marker.position = CLLocationCoordinate2DMake(lat, lng);
    marker.title =  title;
    marker.snippet =  title;
    marker.map = mapView_;
}

- (void)mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(GMSMarker *)marker {
    //Your code goes here
}

-(void) onError : (NSString *) message
{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
- (IBAction)search:(id)sender {
   
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
    [mapView_ clear];
    NSString *searchStr = [self.searchTxt.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if(searchStr.length > 0){
        [self.searchTxt resignFirstResponder];
        GetSearchData *gsd = [GetSearchData new];
        [gsd setServiceListener:self];
        [gsd getCoordinates : self.searchTxt.text];
    }
}
@end


Below is the code that searches for location in the Google Maps and return the latitude and longitude.

GetSearchData.h

#import <Foundation/Foundation.h>

// Delegate

@protocol ServiceListener<NSObject>

@optional

-(void) onSuccess :  (NSMutableArray *)jsonArray;
-(void) onError : (NSString *) message;

@end

@interface GetSearchData : NSObject


@property (nonatomic, retain) id<ServiceListener> listener;
@property (nonatomic, retain) NSDictionary *searchDic;

-(void) setServiceListener : (id <ServiceListener>) listener;
-(void) getCoordinates : (NSString *) searchLocation;

@end

GetSearchData.m

#import "GetSearchData.h"

@implementation GetSearchData

@synthesize listener, searchDic;

-(void) getCoordinates : (NSString *) searchLocation
{
    NSMutableURLRequest *request = [NSMutableURLRequest new];
    NSString *url = [@"https://maps.googleapis.com/maps/api/geocode/json?address=" stringByAppendingString:searchLocation];
    
    request.timeoutInterval = 100.0;
    [request setURL:[NSURL URLWithString:url]];
    
    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){
           
           if(nil != data)
           {

               NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data
                                                                    options:NSJSONReadingMutableContainers
                                                                      error:&error];
               NSLog(@"loans: %@", jsonArray);
               
               dispatch_async(dispatch_get_main_queue(), ^{
                  [self.listener onSuccess:jsonArray];
               });
               
           }
           if (error) {
               NSLog(@"Response %@",error.localizedDescription);
               dispatch_async(dispatch_get_main_queue(), ^{
                   [self.listener onError:error.localizedDescription];
               });
           }
       }];

}

-(NSString *) getValueWithKey :(NSString *) key fromDictionary:(NSDictionary *) dict
{    
    return [[dict objectForKey:key] objectForKey:@"text"];
}

//This function will set the delegate
-(void) setServiceListener : (id <ServiceListener>) theListener
{
    self.listener = theListener;
}


@end

Compile it and run…

Please leave your valuable comments below.

Microsoft’s Brave Move – Universal Windows Platform Bridges

The Universal Windows Platform is a single app platform that is available across all Windows device families, enabling you to reach a new user base and open up new revenue opportunities. From PCs to tablets, phones, HoloLens, Surface Hub, and soon to include Xbox and Raspberry Pi – you can reach all these devices and look great on them all using one store and one codebase.

Following the launch of Windows 10, we are also releasing four Universal Windows Platform Bridge toolkits that enable you to quickly bring your existing code base to the Universal Windows Platform and add capabilities such as live tiles, active notifications, and Windows Store in-app purchases. Each toolkit provides you with tools and run-time technologies that are tailored for your codebase.

Android Runtime

For existing Android™ developers, ”Project Astoria” will enable you to build apps using Android code to target Windows 10 phones without having to leave your Android IDE.

In addition to extending the IDE, ”Project Astoria” will include a Windows phone emulator and interop capabilities that help your app (including UI and services) to run and look great on the Windows platform.

More information about ”Project Astoria” will be made available in Summer 2015, but in the meantime we are offering an invite-only preview for those interested in giving early feedback.

iOS

For existing iOS® developers, ”Project Islandwood” will enable you to build a universal Windows app from within Visual Studio 2015 using your existing Objective-C® code.

You will be able to import your Xcode® project into Visual Studio, tailor the app experience to run on each Windows device family, and extend your iOS code to take advantage of Universal Windows Platform capabilities.

More information about ”Project Islandwood” will be made available in Summer 2015, but in the meantime we are offering an invite-only preview for those interested in giving early feedback.

You can read more from here…

How to use Download manager in Android -A Simple Example.

The download manager is a system service that handles long-running HTTP
downloads. Clients may request that a URI be downloaded to a particular
destination file. The download manager will conduct the download in the
background, taking care of HTTP interactions and retrying downloads
after failures or across connectivity changes and system reboots.

Download Manager in Android

For starting a download you can use the below code.

mManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
   Request mRequest = new Request(Uri.parse(URL));
   mRequest.setDescription("This is a demo File");
// mRequest.setDestinationUri(Uri.parse("give your local path"));
   idDownload = mManager.enqueue(mRequest);
		
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {		mRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE 
				| DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
   }
   else
   {
    	mRequest.setShowRunningNotification(true);
   }


To remove a download…


	mManager.remove(idDownload);

Note that you can have your custom downloads folder using the below code


	mRequest.setDestinationUri(Uri.parse("give your local path"));

To open the Downloads folder.

	public void viewDownload() {
		Intent mView = new Intent();
		mView.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
		startActivity(mView);
	}

To Listen to the Download Status, You will need a BroadcastReceiver.
So create a java file that extends BroadcastReceiver and name it “DownloadStatusReceiver”.

package com.coderzheaven.downloadmanagerdemo;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class DownloadStatusReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equalsIgnoreCase(
                DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
            Toast.makeText(context, "Download Complete", Toast.LENGTH_LONG)
                    .show();
        }
        if (intent.getAction().equalsIgnoreCase(
                DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
            Toast.makeText(context, "Download Notification Clicked", Toast.LENGTH_LONG)
                    .show();
            Intent i = new Intent(context,MainActivity.class);
            i.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK);
            i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
            context.startActivity(i);    
        }
    }
}

This is how you register the receiver in activity.


	@Override
	protected void onStart() {
		super.onStart();
		mDownloadReceiver = new DownloadStatusReceiver();
		registerReceiver(mDownloadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mDownloadReceiver);
	}

This is the Complete source code of the MainActivity.

package com.coderzheaven.downloadmanagerdemo;

import java.io.FileNotFoundException;

import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity implements OnClickListener {

	Button btnStartDwnld, btnRemoveDownload, btnOpenDownloads;
	long idDownload;
	DownloadManager mManager;
	DownloadStatusReceiver mDownloadReceiver;
	public static final String URL = "link to download file";

	@Override
	protected void onStart() {
		super.onStart();
		mDownloadReceiver = new DownloadStatusReceiver();
		registerReceiver(mDownloadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mDownloadReceiver);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		btnStartDwnld = (Button) findViewById(R.id.button1);
		btnRemoveDownload = (Button) findViewById(R.id.button2);
		btnOpenDownloads = (Button) findViewById(R.id.button4);

		btnStartDwnld.setOnClickListener(this);
		btnRemoveDownload.setOnClickListener(this);
		btnOpenDownloads.setOnClickListener(this);
	}

	@SuppressWarnings("deprecation")
	void startDownload() {
		mManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
		Request mRequest = new Request(Uri.parse(URL));
		mRequest.setDescription("This is a demo File");
		// mRqRequest.setDestinationUri(Uri.parse("give your local path"));
		idDownload = mManager.enqueue(mRequest);
		
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
			mRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE | DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
       }
       else
       {
    	   mRequest.setShowRunningNotification(true);
       }
	}

	public void viewDownload() {
		Intent mView = new Intent();
		mView.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
		startActivity(mView);
	}

	void openDownloadedFile() {
		try {
			mManager.openDownloadedFile(idDownload);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			showToast("File has been removed");
		}
	}

	void removeDownload() {		
		mManager.remove(idDownload);
        // This will result in error because we have removed the file.
		openDownloadedFile();
	}

	private void showToast(String message) {
		Toast.makeText(this, message, Toast.LENGTH_LONG).show();
	}

	@Override
	public void onClick(View v) {
		if (v == btnStartDwnld) {
			startDownload();
		} else if (v == btnRemoveDownload) {
			removeDownload();
		} else {
			viewDownload();
		}
	}
}

You can download the source code from here.

Please leave your valuable comments…

How to download files from your FTP to your Android Device?

Hi developers,

This example shows how to download files from your FTP server to your Android device using ApacheFTP Library.

Initially we will be downloading the FTP folder structure.

After FTP structure Download, all the file urls for download will be available in the “DownloadedFileModel” model class, which you can use to
download files individually and save to your desired location. Here I am saving the files to the “files” folder inside the application sandbox.

I have created this project as a library which you can download from this link.
You need to add this project into your project as a library to work.

The usage in your activity would be like this.


	Listener metadataDownloadListener;
	
	//Set the listener first
	setMetaDataDownloadListener();
	
	//Start FTP Structure Download
	FTPService ftp = new FTPService(this, metadataDownloadListener);
	ftp.setCredentials(getString(R.string.ftp_username), getString(R.string.ftp_password));
	ftp.setParentServerFolder(getString(R.string.ftp_parent_folder));
	ftp.start();
	

“ftp_parent_folder” will be something like “/public_html/Your_Folder/Your_Contents”
Also replace with your domain name in the FTPService.java class

	public static final String server = "YOUR_SERVER_DOMAIN";

and the Listener would be


void setMetaDataDownloadListener() {
	metadataDownloadListener = new Listener() {

		@Override
		public void onSuccess(String message) {

		}

		@Override
		public void onError(String message) {
			Logger.logError(TAG, "FTP ERROR");
			tvLoading.setVisibility(View.GONE);
		}

		@Override
		public void onDataReceived(List<DownloadFile> allDownloadedFilesList) {
			Logger.logInfo(TAG, "Download files count : " + allDownloadedFilesList.size());

			Downloader downloader = new Downloader(HomePage.this, allDownloadedFilesList, tvLoading, new DownloadListener() {

				@Override
				public void onError(String message) {
					Logger.logError(TAG, "Error Downloader");						
				}

				@Override
				public void onDownloadComplete() {
					Logger.logInfo(TAG, "All Downloads are complete.");						
				}
			});
			downloader.startDownload();
		}
	};
}
	
	

Pull to Refresh in iOS

Hi everyone..

In today’s tutorial I will be showing a somewhat hidden feature in iOS, the pull to refresh functionality of UITableViews.

Pull to refresh ios

We will jump directly into the code.
First you have to create a sample project with a tableview in the ViewController.

Create an Outlet and link to it.
Add a UIRefreshControl variable also as shown in the below code.

Now your .h file will look like this

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>{
    //Create an object UIRefreshControl
    UIRefreshControl *mRefreshControl;
}
//Outlet of the tableview
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

ViewController.m


#import "ViewController.h"

@interface ViewController ()
{
    NSMutableArray *sampleArray;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"Pull to refresh Demo";
    
    // Do any additional setup after loading the view, typically from a nib.
    
    sampleArray = [NSMutableArray arrayWithObjects:@"Apple", @"Google", @"OnePlus" @"Sony", @"Samsung", nil];
    //Initializing the object and add the target method
    mRefreshControl = [[UIRefreshControl alloc] init];

    [mRefreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
    [self.tableView addSubview:mRefreshControl];
}

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

# pragma Tableview Delegates

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

- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
    
    static NSString *simpleTableIdentifier = @"SimpleTableItem";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }
    cell.textLabel.text=[sampleArray objectAtIndex:indexPath.row];
    return cell;
    
}
/*
 * Method to refresh the tableview
 * @param: Refresh view controller object
 *
 */
- (void)refresh:(UIRefreshControl *)refreshControl {
    
    //Perform the next operation after refresh
    // do your operations
    [self performSelector:@selector(methodAfterRefresh) withObject:nil afterDelay:1.0 ];
   
}

/*
 * Method called after refresh
 *
 */
-(void)methodAfterRefresh{
    
    [sampleArray addObject:@"Newly Added"];
    [self.tableView reloadData];
    //End refresh
    [mRefreshControl endRefreshing];
}
@end

This method will be called when you pull the UITableView.

– (void)refresh:(UIRefreshControl *)refreshControl

Done.

Now go on and run the project.

Download the sample source code from here.

Article Writers Wanted

Hi all,


Ever since I had started my website (coderzheaven.com), I had got very good response from the Visitors and I am happy that my website has helped a lot of people in their day to day work.

Now I am inviting you to write you own articles in my website about any mobile technology you want. You can send your articles to coderzheaven@gmail.com along with your details you want to be published under the post.

This website is purely created to shared knowledge among the programming enthusiasts. So I am expecting that everyone will cooperate and help me in attaining it.

Thanks a lot
James.

Pull-to-refresh libraries in Android.

Hi all…

Today’s article is about pull to refresh libraries for Android.
I think everyone has “GMAIL” app in your phone…So all may have seen a pull to refresh functionality in Gmail application
for Android.

So today I will introduce some of those libraries in Android here…

1. erikwt/PullToRefresh-ListView

Download it from here
https://github.com/erikwt/PullToRefresh-ListView

2. Yalantis/Phoenix

Download from here
https://github.com/Yalantis/Phoenix

3. chrisbanes/Android-PullToRefresh

Download from here
https://github.com/chrisbanes/Android-PullToRefresh

4. fredericojssilva/PullToUpdate-ListView

Get it from here
https://github.com/fredericojssilva/PullToUpdate-ListView

5. TuteCentral

View it here
http://www.tutecentral.com/android-pull-to-refresh/

https://dl.dropboxusercontent.com/u/91846918/CoderzHeaven%20images/PullToRefreshAndroid/pull1.png

https://dl.dropboxusercontent.com/u/91846918/CoderzHeaven%20images/PullToRefreshAndroid/pull2.png

Please leave your valuable comments here

Thankyou.

Create a date in your format in IOS

Below functions takes the current date and time and formats it to give a date-time string.
You can customise it in the way you want.

The string that the below function generates will be like this – 23-Dec-2014 4:23 PM


//Get the current date...
+(NSDate *) getCurrentDate
{
    NSDate *now = [NSDate date];
    return now;
}

//Get the date and time in a formatted way...
+(NSString *) getFormattedDateAndTime
{
    NSDate *now = [Global getCurrentDate];
    int hour;
    NSString *am_pm;
    //Get calendar Instance
    NSCalendar *cal=[NSCalendar currentCalendar];

    //optionally set the Locale
    //NSTimeZone *tz=[NSTimeZone timeZoneWithName:@"America/Chicago"];
    //[cal setTimeZone:tz];

    NSDateComponents *comp=[cal components:NSCalendarUnitHour|NSCalendarUnitMinute fromDate:now];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MMM-yyyy"];
    
    NSString *stringFromDate = [formatter stringFromDate:now];

    hour = (int)[comp hour];
    am_pm = (hour >= 12) ? @"PM" : @"AM";
    
    if(hour >= 12){
        hour = hour - 12;
    }
    
    // 23-Dec-2014 4:23 PM
    NSString *dateTimeStr = [NSString stringWithFormat:@"%@ %d %d %@", 
                            stringFromDate, (int)hour, (int)[comp minute], am_pm];
    
    return dateTimeStr;
}

Use “MMMM” for “December” and “MMM” for “Dec” in month.

A Simple Chat Application in Android Using GCM and Server Side – PHP.

Hi all,

In Today’s Tutorial I will help you to make a simple chat application in Android using Google Cloud Messaging. I am using PHP as server side script.

Here are the things you need to follow to make this application.

1. You need to register to Google for GCM.
2. You need a server where your script resides.[We will use our own system as Server in this application].

Please read this before starting with the application
After reading the above link, you will get a API key and Sender ID , which distinguishes your application.
So you will need it in the code, keep it somewhere safe.

You need to change the API Key inside Android source code in the sample Provided below.
Your API Key and SENDER ID will look something similar to this.

 
 String SENDER_ID = "243750827028";
 String API_KEY   = "AIzaSyCBI_c2izVrEPcJ509uZGVLdfWUAW-rg48";
	

Next Go through this link, till step 2 in that page because I have provided the source code below.

The usual flow of a simple GCM application is like this

1. User launches your application for the first time.
2. Your application will call “register” to register with GCM.
3. Google will send you back a “Registration ID” which will be unique for that device.
But beware these “Registration ID’s” will change when you update the application or reinstall it after uninstalling. So don’t use it to uniquely identify a user. A username/password combination or a Phone Number usually does the trick.

4. The device gets the “Registration ID” and store it locally, so that the device don’t need to register again each time the user run the
application.
5. Send this registration ID to your server and Store it there along with a unique identifier for the user. [Here we will use ‘username’ for the time being].
6. When the user taps send message button you need to call a server side script that will communicate with GCM server which will
send this message to corresponding device.
ie. User taps the button -> send the device_reg_id and message to your server -> send these parameters from your server to GCM
-> GCM send the message to Device identified by reg id.

So I am not going to paste the whole code here.
You can directly download it from below links

Client Complete Android source code.

PHP server side source code.

Here I have used a simple database structure for simplicity.
I am using username for identifying each user.

You need to make the same structure for the below sample to work.

GCM Sample DB structure

GCM Sample DB structure

For Server Side I am using XAMPP for Mac.
You can download the Server side source code and put it inside htdocs folder inside XAMPP/Applications.

Start your servers.

Please check the Screenshot below.

GCM Sample DB structure

Then Go to your browser and type “localhost”. if your server is running, then you will see “phpMyAdmin” Page.

For testing it in your system and in your device, Both should be in the same network, for example : both should be in the same WIFI netwrok of your home.
Please type “ifconfig” for Mac in terminal and check inside “en0″ or “en1″ to get your sytem IP. For Windows type “ipconfig”.

Before running the application change the “IP” in the Utils file.

I am not going to the Android source code because Complete source is already provided.

How to test?

1. Change the API Key and Sender ID in the application.

2. Make sure server side is set up. copy php code to your local server as described above.
Make sure you have sql tables set up.

3. Make sure your servers are running.

4. Your testing devices and Your server should be on the same network, otherwise you have to host an online server. You can use the Emulator also as one device, but it should be an emulator with “Google Play Services”. Android 5.0 is good to go.

5. Change the IP address in “Utils.java” to your system IP address.

Please leave your comments if you have problems understanding the above article.

How to connect Localhost in your MAC or Windows to your Android Device OR Android Emulator ?

The name “localhost” is just a loopback to your own computer.

1. ACCESSING LOCALHOST ON ANDROID DEVICE.

To access it on your Android Device, you need to find the computer’s IP address.

  • The most general way of finding this info, which works on both Mac and Linux, is to go into the Terminal and type “ifconfig” AND for Windows type “ipconfig” in the command prompt.
  • Look for either “en0″ or “en1″, and under that entry look for the “inet” listing. It will be something along the lines of “192.168.1.100”.
  • When you find that address, that’s what you’ll want to put in your browser’s address bar or the URL in the code you want to call your MAC’s/Windows’ localhost.
  • On a Mac specifically,

    Go to System preferences/sharing OR just search on right top – remote management

    Make sure remote management is checked

Note : MAKE SURE THAT YOUR ANDROID DEVICE AND YOUR MAC/WINDOWS ARE ON THE SAME NETWORK OTHERWISE IT WILL NOT WORK. [EG : SAME WIFI NETWORK].

For Example in the Android code you can use like below and call a webservice that is residing in your local server, i.e your localhost.


 new HttpPost("http://192.168.0.101/your_localhost_folder/your_localhost_file.php");

2. ACCESSING LOCALHOST ON ANDROID EMULATOR.

You can have the same thing as described above for Android Emulator also as long as they are in same network.

But there are other options too…

You can check it in the post here.

IN App Purchase – Android – Simplified source code

Hi all,

I have already showed you how to implement in app purchase in Android.
Please go through this post before reading this article.

Android IN App Purchase

This is how the MainActivity source code will look like.

package com.coderzheaven.inappdemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.coderzheaven.android.util.IabHelper;
import com.coderzheaven.inapp.InAppPurchase;
import com.coderzheaven.inapp.InAppStateListener;

public class MainActivity extends Activity implements OnClickListener,
		InAppStateListener {

	static final String TAG = "INAPPTESTING";

	// INAPP
	IabHelper mHelper;
	InAppPurchase inapp;
	static String SKU_INAPPITEM_ID = "android.test.purchased";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

	}

	@Override
	public void onClick(View v) {

		if (v.getId() == R.id.button_query) {

			showToast("Querying Items");
			inapp = new InAppPurchase(this, this, SKU_INAPPITEM_ID);
			mHelper = inapp.QueryInventry();

		} else {

			if (inapp != null)
				inapp.initiatePurchase();
			else
				showToast("Please click query items before purchasing");

		}

	}

	public void showToast(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
		;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + ","
				+ data);

		// Pass on the activity result to the helper for handling
		if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
			// not handled, so handle it ourselves (here's where you'd
			// perform any handling of activity results not related to in-app
			// billing...
			super.onActivityResult(requestCode, resultCode, data);
		} else {
			Log.d(TAG, "onActivityResult handled by IABUtil.");
		}
	}

	// IN APP PURCHASE LISTENERS

	@Override
	public void onInAppInitialiseError() {
		System.out.println("onInAppInitialiseError");
		showToast("In App initialise Error.");
	}

	@Override
	public void onInAppInitialiseSuccess() {
		System.out.println("onInAppInitialiseSuccess");
		showToast("In App initialise Success.");
	}

	@Override
	public void onQueryInventryCompleted() {
		System.out.println("onQueryInventryCompleted");
		//showToast("Querying Items Completed.");
	}

	@Override
	public void onQueryInventryError(String message) {
		System.out.println("onQueryInventryError : ");
		showToast("Querying Items Error.");
	}

	@Override
	public void onAlreadyPurchased(String inappItemID) {
		System.out.println("onAlreadyPurchased");
		showToast("Item already Purchased.");
	}

	@Override
	public void onItemNotPurchased(String inappItemID) {
		System.out.println("onItemNotPurchased : " + inappItemID);
		showToast("Item not purchased");
	}

	@Override
	public void onPurchaseSuccessfull(String inappItemID) {
		System.out.println("onPurchaseSuccessfull : " + inappItemID);
		showToast("Purchase Successful");
	}

	@Override
	public void onPurchaseError(String inappItemID, String message) {
		System.out.println("onPurchaseError : " + inappItemID);
		showToast("Purchase Error");
	}

}

You can download the complete source code from here itself.

Creating Tabs dynamically in ios with dynamic tab controller.

This article covers how do you create a tab based application in an ISOS Application.

Tabs in IOS

At first you Create a new Project and Click on Single View Application and name it accordingly.

After creation of the project, open the storyboard and you can see a single view controller which is connected to class ViewController.

Just drag a place a label inside that view controller and changes it’s text to say “Tab content”.

Create a new Tab2ViewController.h and Tab2ViewController.m files by copying ViewController.h and .m for now. You can have your own ViewController.

Now drag a new controller to the storyboard and set its Class in the attributes inspector to “Tab2ViewController”
[Make sure you set the class otherwise the app will not connect that NIB to the corresponding class].

The important thing.

You need to set the StoryBoardID for each NIB in the attributes inspector.

Take a look at the below Screenshot.

Tabs in IOS

Now we have two view controllers

Your storyboard should look like this now.

Tabs in IOS

we are going to create 5 tabs dynamically and keep each view controller alternately for now.
You can have 5 different view controllers and place it on each tab.

Go to App Delegate.h and create a varaible for TabbarController.

AppDelegate.h


#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>{
    
    UITabBarController *tabBarController;
    
}

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) UITabBarController *tabBarController;

@end


Now go to AppDelegate.m and write a function addTabs which is given below.


-(void) addTabs
{
    
    NSMutableArray *listOfViewControllers = [[NSMutableArray alloc] init];
    
    UIStoryboard*  sb = [UIStoryboard storyboardWithName:@"Main"  bundle:nil];
    
    UIViewController* vc0 = [sb instantiateViewControllerWithIdentifier:@"ViewController"];
    [listOfViewControllers addObject:vc0];
    UIViewController *vc1 = [sb instantiateViewControllerWithIdentifier:@"Tab2ViewController"];
    [listOfViewControllers addObject:vc1];
    UIViewController *vc2 = [sb instantiateViewControllerWithIdentifier:@"ViewController"];
    [listOfViewControllers addObject:vc2];
    UIViewController *vc3 = [sb instantiateViewControllerWithIdentifier:@"Tab2ViewController"];
    [listOfViewControllers addObject:vc3];
    UIViewController *vc4 = [sb instantiateViewControllerWithIdentifier:@"ViewController"];
    [listOfViewControllers addObject:vc4];
    
    
    tabBarController = [[UITabBarController alloc] init];
    [tabBarController setViewControllers:listOfViewControllers   animated:YES];
    
        UITabBar *tabBar = self.tabBarController.tabBar;
        UITabBarItem *item0 = [tabBar.items objectAtIndex:0];
        UITabBarItem *item1 = [tabBar.items objectAtIndex:1];
        UITabBarItem *item2 = [tabBar.items objectAtIndex:2];
        UITabBarItem *item3 = [tabBar.items objectAtIndex:3];
        UITabBarItem *item4 = [tabBar.items objectAtIndex:4];
        //UITabBarItem *item5 = [tabBar.items objectAtIndex:5];
    
        NSArray *tabTitles = [NSArray arrayWithObjects:@"Tab 1", @"Tab 2", @"Tab 3", @"Tab 4", @"Tab 5", nil];
    
        [item0 initWithTitle:tabTitles[0] image:[UIImage imageNamed:@"tab1_img.png"] selectedImage:[UIImage imageNamed:@"tab1_img.png"]];
        [item1 initWithTitle:tabTitles[1] image:[UIImage imageNamed:@"tab1_img.png"] selectedImage:[UIImage imageNamed:@"tab1_img.png"]];
        [item2 initWithTitle:tabTitles[2] image:[UIImage imageNamed:@"tab1_img.png"] selectedImage:[UIImage imageNamed:@"tab1_img.png"]];
        [item3 initWithTitle:tabTitles[3] image:[UIImage imageNamed:@"tab1_img.png"] selectedImage:[UIImage imageNamed:@"tab1_img.png"]];
        [item4 initWithTitle:tabTitles[4] image:[UIImage imageNamed:@"tab1_img.png"] selectedImage:[UIImage imageNamed:@"tab1_img.png"]];
    
    [self.window addSubview:self.tabBarController.view];
    
    tabBarController.view.autoresizingMask=(UIViewAutoresizingFlexibleHeight);
    self.window.rootViewController = tabBarController;
}


make sure you have an image named “tab1_img.png” image in your project folder.

Now call the above function in

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

	[self addTabs];
	
	return YES;
}

The whole AppDelegate.m looks like this.


#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

@synthesize tabBarController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    [self addTabs];
    
    return YES;
}


-(void) addTabs
{
    
    NSMutableArray *listOfViewControllers = [[NSMutableArray alloc] init];
    
    UIStoryboard*  sb = [UIStoryboard storyboardWithName:@"Main"  bundle:nil];
    
    UIViewController* vc0 = [sb instantiateViewControllerWithIdentifier:@"ViewController"];
    [listOfViewControllers addObject:vc0];
    UIViewController *vc1 = [sb instantiateViewControllerWithIdentifier:@"Tab2ViewController"];
    [listOfViewControllers addObject:vc1];
    UIViewController *vc2 = [sb instantiateViewControllerWithIdentifier:@"ViewController"];
    [listOfViewControllers addObject:vc2];
    UIViewController *vc3 = [sb instantiateViewControllerWithIdentifier:@"Tab2ViewController"];
    [listOfViewControllers addObject:vc3];
    UIViewController *vc4 = [sb instantiateViewControllerWithIdentifier:@"ViewController"];
    [listOfViewControllers addObject:vc4];
    
    
    tabBarController = [[UITabBarController alloc] init];
    [tabBarController setViewControllers:listOfViewControllers   animated:YES];
    
        UITabBar *tabBar = self.tabBarController.tabBar;
        UITabBarItem *item0 = [tabBar.items objectAtIndex:0];
        UITabBarItem *item1 = [tabBar.items objectAtIndex:1];
        UITabBarItem *item2 = [tabBar.items objectAtIndex:2];
        UITabBarItem *item3 = [tabBar.items objectAtIndex:3];
        UITabBarItem *item4 = [tabBar.items objectAtIndex:4];
        //UITabBarItem *item5 = [tabBar.items objectAtIndex:5];
    
        NSArray *tabTitles = [NSArray arrayWithObjects:@"Tab 1", @"Tab 2", @"Tab 3", @"Tab 4", @"Tab 5", nil];
    
        [item0 initWithTitle:tabTitles[0] image:[UIImage imageNamed:@"tab1_img.png"] selectedImage:[UIImage imageNamed:@"tab1_img.png"]];
        [item1 initWithTitle:tabTitles[1] image:[UIImage imageNamed:@"tab1_img.png"] selectedImage:[UIImage imageNamed:@"tab1_img.png"]];
        [item2 initWithTitle:tabTitles[2] image:[UIImage imageNamed:@"tab1_img.png"] selectedImage:[UIImage imageNamed:@"tab1_img.png"]];
        [item3 initWithTitle:tabTitles[3] image:[UIImage imageNamed:@"tab1_img.png"] selectedImage:[UIImage imageNamed:@"tab1_img.png"]];
        [item4 initWithTitle:tabTitles[4] image:[UIImage imageNamed:@"tab1_img.png"] selectedImage:[UIImage imageNamed:@"tab1_img.png"]];
    
    [self.window addSubview:self.tabBarController.view];
    
    tabBarController.view.autoresizingMask=(UIViewAutoresizingFlexibleHeight);
    self.window.rootViewController = tabBarController;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end

All done.

Just Go on and run the application.

You can download the complete source code from here.

Making a GridView in iOS using UICollectionView.

Hey all,

In Today’s article you will study about the implementation of UICollectionView in iOS.
It is similar to GridView in Android.

UICollectionView in iOS

First drag a UICollectionView [Not the Collection View Controller] in your interface and let it be there.
we will come back to it later.

We are going to create a UICollectionView with custom Cells.

So for that we will first create a class for the Custom Rows in the UICollection.
For that Go to Project->right Click-> Add new File -> Cocoa files -> name it “CustomCollectionCell” and extends UICollectionViewCell

UICollectionView in iOS

CustomCollectionCell.h

#import <UIKit/UIKit.h>

@interface CustomCollectionCell : UICollectionViewCell
{
   
}

@property (nonatomic, strong) IBOutlet UILabel *collectionLabel;
@property (nonatomic, strong) IBOutlet UIImageView *collectionImage;

@end

CustomCollectionCell.m

#import "CustomCollectionCell.h"

@implementation CustomCollectionCell

@end

Now you will notice that there will be a new UICollection row in the hierarchy of the interface in which
the UICollectionView is placed.

UICollectionView in iOS

Now after selecting the cell row from the hierarchy go to the attributes inspector and set the class
name as “CustomCollectionCell” as shown in the Screenshot below.

UICollectionView in iOS

Also set the “identifier” as “CollectionCell”.

UICollectionView in iOS

Now place an “ImageView” and “Label” inside the label and connect it to the variables in the CustomCollectionCell,collectionImage and collectionLabel.

Now we will go to the controller that implements the UICollectionView.

Like TableViews UICollectionView also has delegate methods.

So Add the delegate to the ViewController.h

We will set the Datasource and Delegate in the code itself.

ViewController.h



#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>{
   
    NSArray *image_array, *label_array;
    
}

@property(nonatomic, weak) IBOutlet UICollectionView *collectionView;


@end

In the above code we have a variable for the UICollectionView, so please hook it to the outlet before proceeding otherwise you will see nothing in the interface.

ViewController.m

#import "ViewController.h"
#import "CustomCollectionCell.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize collectionView;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    image_array = [NSArray arrayWithObjects: @"apple.png", @"android.png", @"apple.png", @"android.png",@"apple.png", @"android.png",@"apple.png", @"android.png", nil ];
    label_array = [NSArray arrayWithObjects: @"APPLE", @"ANDROID",@"APPLE", @"ANDROID", @"APPLE", @"ANDROID",
                   @"APPLE", @"ANDROID", nil ];
    
    collectionView.delegate = self;
    collectionView.dataSource = self;
    
    CGRect rect = collectionView.frame;
    rect.origin.x = 5;
    rect.origin.y = 0;
    rect.size.width = [[UIScreen mainScreen] bounds].size.width - 5;
    rect.size.height = [[UIScreen mainScreen] bounds].size.height;
    
    collectionView.frame = rect;
    
    collectionView.backgroundColor = [UIColor clearColor];
}


-(void) setBorder:(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;
}

#pragma mark - UICollectionView Datasource
// 1
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {
    return [image_array count];
}
// 2
- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
    return 1;
}
// 3
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *simpleTableIdentifier = @"CollectionCell";
    
    CustomCollectionCell *cell = [cv dequeueReusableCellWithReuseIdentifier:simpleTableIdentifier forIndexPath:indexPath];
    cell.collectionLabel.text = [label_array objectAtIndex:indexPath.row];
    cell.collectionImage.image = [UIImage imageNamed: [image_array objectAtIndex:indexPath.row]];
    
    if(indexPath.row % 2 == 0)
        [self setBorder:cell withBGColor:[UIColor greenColor] withCornerRadius:3.0 andBorderWidth:0.5 andBorderColor:[UIColor redColor] WithAlpha:1.0];
    else
        [self setBorder:cell withBGColor:[UIColor redColor] withCornerRadius:3.0 andBorderWidth:0.5 andBorderColor:[UIColor redColor] WithAlpha:1.0];
    
    return cell;
}
// 4
/*- (UICollectionReusableView *)collectionView:
 (UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
 {
 return [[UICollectionReusableView alloc] init];
 }*/


#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Clicked %d", indexPath.row);
}
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {

}

#pragma mark – UICollectionViewDelegateFlowLayout

// 1
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGSize s = CGSizeMake([[UIScreen mainScreen] bounds].size.width/2 - 8, [[UIScreen mainScreen] bounds].size.height/2-70);
    return s;
}

// 3
- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(5, 0, 5, 5);
}

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

@end

All done, Just go on and run the application.

You can download the complete source code from here.

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.