Wednesday, February 13, 2013

Simple UICollectionView Sample

Here i am giving you an easy sample for UICollectionView. and you can learn how to use the UICollectionView in simple way.

1. First of all drag UICollectionView inside UIView, where you want to show UICollectionView.

2. Now set the property of UICollectionView by clicking show the Size Inspector, 2nd Last tab.
   - Here you can set the Cell Size, as per you required. (lets assume wd: 300, ht: 300)
   - You can set the gap also between cell.

3. Now go for its class file i.e. in  ".h". and add following code also add IBOutlet for the UICollectionView

#import <UIKit/UIKit.h>

@interface ProjectsViewController : UIViewController <UICollectionViewDataSource, UICollectionViewDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *projectListView;


4. Now go for its ".m" file and add the following code in viewDidLoad

[self.projectListView registerNib:[UINib nibWithNibName:@"ProjectCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"projectCell"];

5. Now add the following functions, which is necessary for the UICollectionViewDelegate and datasource.

- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section{
    return [projectList count]; // Returns the total object counts
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath;
    ProjectCollectionViewCell *cell = (ProjectCollectionViewCell *)[cv dequeueReusableCellWithReuseIdentifier:@"projectCell" forIndexPath:indexPath];
    NSString *imagePath = [NSString stringWithFormat:@""];
    NSURL *imageURL = [NSURL URLWithString:imagePath];
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
    cell.projectImage.image = [UIImage imageWithData:imageData];
    return cell;

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

6. Before you get proceed, You have to take one more action
  - Create Cell class wit the name of  ProjectCollectionViewCell
  - for this Just create new Objective-C Class with Subclass of UICollectionViewCell
  - This will not create any XIB for this. So create a new File as User Interface>Empty
  - Now Go in xib file and drag Collection View Cell in empty space
  - And Drag UIImageView inside Collection View Cell, set the IBOutlet for this UIImage (i have taken projectImage) .
  - Now just click the Collection View Cell and set the Class (in identifier inspector) name as ProjectCollectionViewCell.
  - And Set the Identifier (in attributes Inspector) as projectCell. (can put any name)

Thats it :) Now check every step in step 5.

UICollectionView handles Lazy Loading itself, which handled the image loading at run time. It will just load the image, which is in the screen.

1. Some time delegate function numberOfItemsInSection or cellForItemAtIndexPath didn't call.
No worry about this, Just follow the following steps

 - You must added delegates and data source in .h file as

<UICollectionViewDataSource, UICollectionViewDelegate>
 - Now add following code to load it perfectly, where you required

[projectListView reloadData];

Thursday, February 7, 2013

send Data with Observer in xCode

I have gone through many sites, but found the logic, of this, in below link

and it works like this.

NSData *responseData = [request responseData];
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"setProjectListFromServer" object:nil userInfo:res];

//You can add your data with userInfo

Now to receive this. add following code
First add the listener for this event as follow

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(projectListFromServer:) name:@"setProjectListFromServer" object:nil];

Now to get the detail of response from server, do as follow -
-(void)projectListFromServer:(NSNotification *) response
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    for(id key in response.userInfo) {

In Case of passing a simple NSString You can pass via

[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:@"value"];

And to receive this you can take like this,

First add the listener like

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incomingNotification:) name:@"notificationName" object:nil];

Now Use this like

- (void) incomingNotification:(NSNotification *)notification{
    NSString *theString = [notification object];

Wednesday, February 6, 2013

How addObserver works in xCode

Follow the following steps for addObserver

1. From where you want to listen the Observer, add the following lines inside your event function

Supose its Aclass.m

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:@"loginSuccessNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginFailure) name:@"loginFailureNotification" object:nil];

2. Now add the postNotification in the class from where you want to dispatch for this

        [[NSNotificationCenter defaultCenter] postNotificationName:@"loginSuccessNotification" object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"loginFailureNotification" object:nil];

3. Now remove this Notification when you have done

- (void) loginSuccess {
    [[NSNotificationCenter defaultCenter] removeObserver:self];

- (void)loginFailure {
    [[NSNotificationCenter defaultCenter] removeObserver:self];

Work with ASIHTTPRequest for simple Login in xCode

Hi,  As i have gone through multiple sites to maintain the User Session for multiple calls after login. And User session needs to retain. Then i found ASIHTTPRequest API for Objective C. You can download that from here.

Now the coding part
First You need to declare the delegate in you class (.h) file as follow

#import "ASIHTTPRequest.h"

@interface ConnectionControl : NSObject <ASIHTTPRequestDelegate>

Now for simple login with server, which returns JSON, Follow the code below

-(void) userLoginFromServer:(NSString *)userId andPassword:(NSString *)password
    NSURL *loginURL = [NSURL URLWithString:@""];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:loginURL];
    [request setRequestMethod:@"POST"];
    //Following code will retain username and password for Re-login.
    [request setUsername:userId];
    [request setPassword:password];
    [request setUseKeychainPersistence:YES];
    [request addPostValue:userId forKey:@"username"];
    [request addPostValue:password forKey:@"password"];
    [request setDelegate:self];
    [request setTimeOutSeconds:60];
    [request startSynchronous];
    [request setUseSessionPersistence:YES];

- (void)requestFailed:(ASIHTTPRequest *)request {
    printf("Some Problem");

- (void)requestFinished:(ASIHTTPRequest *)request
    NSData *responseData = [request responseData];
NSString *authJsonString = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
    NSDictionary *res = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:nil];
    for(id key in res) {
        id value = [res objectForKey:key];
        NSString *keyAsString = (NSString *)key;
        NSString *valueAsString = (NSString *)value;
        NSLog(@"\nkey: %@", keyAsString);
        NSLog(@"value: %@", valueAsString);
- (void)requestStarted:(ASIHTTPRequest *)request{
    NSLog(@"request started");

Monday, February 4, 2013

Check JSON String which is 0 or 1


 As i have gone through with the JSON String check wether its 0 or 1. Then found NSCFBoolean conversion issue. And iOS 6 doesn't support NSCFBoolean conversion so to resolve this, Following is the best

As my previous blog about the JSON integration, if value is 0 or 1 as in below code.

for(id key in res) {
        id value = [res objectForKey:key];

        NSString *keyAsString = (NSString *)key;
        NSString *valueAsString = (NSString *)value;
You can check value with 0 or 1 with Boolean, as follow
[value boolValue] == YES
or directly if(![value boolValue])

Friday, February 1, 2013

xCode and JSON Connection in iOS 6.0

I Tried with ASIHttpRequest but found that it will not work in iOS 6.0 because ARC is not supported in ASIHttpRequest. And googled a lot for the POST method connection to PHP. So finally i found the NSMutableURLRequest method for safe and reliable. So here is the method to call a simple Login Feature.

1. First Declare NSMutableData as follow

@interface LoginViewController ()
@property (nonatomic, strong) NSMutableData *responseData;

2. Now initiate this Data in viewDidLoad as follow

self.responseData = [NSMutableData data];

3. Send you User id and password to JSON by following method

-(void)connectForCredential:(NSString *)userId andPassword:(NSString *)userPassword
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@""]];
    NSString *postString = [NSString stringWithFormat:@"username=%@&password=%@",userId, userPassword];
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request
    if (connection) {
    else {}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    [self.responseData setLength:0];
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    [self.responseData appendData:data];
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    printf("Data Failure");

// Following function will show you the result mainly
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    printf("\nSucceeded! Received %d bytes of data\n",[self.responseData length]);
    // convert to JSON
    NSError *myError = nil;
    NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
    // show all values
    for(id key in res) {
        id value = [res objectForKey:key];
        NSString *keyAsString = (NSString *)key;
        NSString *valueAsString = (NSString *)value;
        NSLog(@"\nkey: %@", keyAsString);
        NSLog(@"value: %@", valueAsString);
    // extract specific value...
    NSArray *results = [res objectForKey:@"results"];
    for (NSDictionary *result in results) {
        NSString *icon = [result objectForKey:@"icon"];
        printf("icon: %@", icon);