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.

    Localhost for Android Emulator and iPhone Simulator.

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

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

    10.0.2.2

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

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

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

    http://localhost:8000/your_path

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

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

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

    Camera Functions in IOS


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

    ViewController.h”

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

    ViewController.m

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

    Customizing UITableView using “Prototype Cells” in iOS.

    Hi all,

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

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

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

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

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

    Now our “Main.storyBoard” looks like this.

    Prototype Cells in iOS

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

    Select Style = ” Basic ”
    Indentifier = “list_item_cell”

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

    Prototype Cells in iOS

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

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

    Our work in the Interface Builder is over.

    Now Lets do the coding part

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

    ViewController.h

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

    Now go to ViewController.m and synthesize the array.

    These are the delegate methods

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

    Now your ViewController.m will look like this.

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

    OK Done. Run the project.

    Prototype Cells in iOS

    Handling Files in iOS

    Hi All,

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

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

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

    Comparing two file contents

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

    Check if writable, readable and executable

     
     if ([fileManager isWritableFileAtPath:@"FilePath"]) {
             NSLog(@"File isWritable");
     }
    
      if ([fileManager isReadableFileAtPath:@"FilePath"]) {
              NSLog(@"File isReadable");
     }
    
    
     if ( [fileManager isExecutableFileAtPath:@"FilePath"]){
              NSLog(@"File is Executable");
     }
    

    Move file

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

    Copy file

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

    Remove file

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

    Read file

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

    Write file

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

    Building Custom Components in Android.

    Hi everyone,

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

    So we will start.

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

    1. XML
    2. Java Code

    1. Using Java Code

    Create a class named CustomTV and extend TextView.

    CustomTV.java

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

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

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

    activity_main.xml

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

    1. Using XML

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

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

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

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

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

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

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

    activity_main.xml

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

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

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

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

    Apply your custom attribute in Java code also.

       tv.setCustomColor("#00FF00");
    

    Delegates in iOS – A Simple Example

    Hi All,

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

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

    So Create .m and .h files for Common.

    Common.h

    #import <Foundation/Foundation.h>
    #import <MessageUI/MessageUI.h>
    
    @interface Common : NSObject{
        
        MFMailComposeViewController *mailComposer;
        
    }
    
    @property (nonatomic, weak) id <MFMailComposeViewControllerDelegate> delegate;
    
    -(void)sendMail:(UIViewController *) cont : (NSString *) mailSubject : (NSString *) mailBody;
    
    -(void) setDelegate:(id <MFMailComposeViewControllerDelegate>)aDelegate;
    
    @end
    
    

    Now Go to Common.m and implement the methods.

    #import "Common.h"
    
    @implementation Common
    
    @synthesize delegate;
    
    -(void)sendMail:(UIViewController *) cont :(NSString *) mailSubject : (NSString *) mailBody{
        
        mailComposer = [[MFMailComposeViewController alloc]init];
        [mailComposer setSubject:mailSubject];
        mailComposer.mailComposeDelegate = delegate;
        [mailComposer setMessageBody:mailBody isHTML:NO];
        [cont presentViewController:mailComposer animated:YES completion:nil];
        
    }
    
    -(void) setDelegate:(id <MFMailComposeViewControllerDelegate>)aDelegate{
        if (delegate != aDelegate) {
            delegate = aDelegate;        
        }
    }
    
    @end
    
    

    Now Go to ViewController.h

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

    #import <UIKit/UIKit.h>
    #import <MessageUI/MessageUI.h>
    
    @interface ViewController : UIViewController<MFMailComposeViewControllerDelegate>
    {
        
    }
    @end
    

    Now in the implementation class

    ViewController.m

    #import "ViewController.h"
    #import "Common.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad
    {
    
        Common *com = [Common new];
        [com setDelegate:self];   // Setting the Mail Composer delegate
        [com sendMail:self :@"Mail Subject" :@"Mail Body"];
        
    }
    
    
    #pragma mark - mail compose delegate
    -(void)mailComposeController:(MFMailComposeViewController *)controller
             didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
        if (result) {
            NSLog(@"Result : %d",result);
        }
        if (error) {
            NSLog(@"Error : %@",error);
        }
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }
    

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