Category: Apple iOS

Consuming Webservices & Parsing JSON Response Tutorial :Part 2

Hi Folks,

This is the Part 2 of  Consuming Webservices & Parsing JSON Response Tutorial

Previously we have consumed webService using NSURLConnection and got the response successfully .

Now time to parse the JSON response and populate data on UITableView.So the question is Is There any external library to parse raw JSON string?

Yes, there is numbers of external JSON framework which makes developers job easy.For this tutorial we are going to use SBJson framework

You can grab this framework from here and if you have not read part 1 just go through it here

How to install JSON framework?

The simplest way to start using JSON in your application is to copy all the source files (the contents of the Classes folder) into your own Xcode project.

  1. In the Finder, navigate into the Classes folder.
  2. Select all the files and drag-and-drop them into your Xcode project.
  3. Tick the Copy items into destination group’s folder option.
  4. Use #import “SBJson.h” in your source files.

Parsing Raw JSON

The first thing you should do, if you do not understand exactly what’s going on, is to NSLog thedescription of the JSON parser output. This will be a “list” of NSDictionary and NSArray, and when you see the description output you will understand that there is a one-to-one mapping of JSON “object” to NSDictionary

I have created one method where my parsing logic goes

declare it in .h file

-(NSMutableArray *)parseJsonResponse:(NSString *)rawJsonResponse;

in .m file implement this method as

-(NSMutableArray *)parseJsonResponse:(NSString *)rawJsonResponse

{

NSArray *responseKeyValueArray;

NSError *error;

SBJSON *json = [[SBJSON new] autorelease];

NSDictionary *responseKeyValueDict = [json objectWithString:rawJsonResponse error:&error];

#if DEBUG

NSLog(@”JSON parsing responseKeyValueDict: %@”, responseKeyValueDict);

#endif

if (responseKeyValueDict == nil)


{

#if DEBUG

NSLog(@”JSON parsing failed: %@”, [error localizedDescription]);

#endif

}

else {

if([responseKeyValueDict  valueForKey:@”list”] )

{

responseKeyValueArray  =[responseKeyValueDict  valueForKey:@”list”];

#if DEBUG

NSLog(@”responseKeyValueArray ::%@”,responseKeyValueArray);

#endif

if ([responseKeyValueArray isKindOfClass:[NSArray class]])

{

NSMutableArray *artistdetails = [[NSMutableArray alloc]init];

for(int i=0;i<[responseKeyValueArray count];i++)

{

NSDictionary *keyValueIndex = [responseKeyValueArray objectAtIndex:i];

#if DEBUG

NSLog(@”keyValueIndex::%@”,keyValueIndex);

#endif

Artist *artist=[[Artist alloc]init];

artist.imageName=[keyValueIndex objectForKey:@”image”];

artist.artistName=[keyValueIndex objectForKey:@”name”];

#if DEBUG

NSLog(@”artist.artistName::%@”,artist.artistName);

#endif

[artistdetails addObject:artist];

[artist release];

}

#if DEBUG

NSLog(@”artistdetails %d”,[artistdetails count]);

#endif

return [artistdetails autorelease];

}

else

{

return nil;

}

}

}

return  nil;

}

Call this method in connectionDidFinishLoading .modify it as

– (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

// do something with the data

// receivedData is declared as a method instance elsewhere

NSLog(@”Succeeded! Received %d bytes of data”,[receivedData length]);

NSString *responseString = [[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding] autorelease];

NSLog(@”Succeeded! Received JSON String %@ “,responseString);

// parse raw json response

parsedResponseData=[self parsedJsonResponse:responseString];

// release the connection, and the data object

[connection release];

[receivedData release];

}

Now we have Artist information, populate data over UITableView.To achieve this reload tableview and modify you cell for row method as below.

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

static NSString *CellIdentifier = @”ArtistCell”;

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

}

if([parsedResponseData count]!=0)

{

// Configure the cell.

Artist *a = [parsedResponseData objectAtIndex:indexPath.row];

NSLog(@”artist name isin cellfor index path %@”,a.artistName);

NSLog(@”artist image link is %@”,a.imageName);

cell.imageView.image=[self displayImage:a.imageName];

cell.textLabel.text=a.artistName;

}

else

{

if(indexPath.row==0)

{

cell.textLabel.text=@”No Data”;

}

}

return cell;

}

 

To display images to UIImage of table view cell add and implement one more method

-(UIImage*)displayImage:(NSString *)imageUrl

{

NSData* imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:imageUrl]];

UIImage* image = [[UIImage alloc] initWithData:imageData];

return image;

}

Done 🙂

Note:Although you might expect some UI Freeze while scrolling as there is no Lazy Loding of image.To resolve this just keep it your uitableview scroll disable.

Hit run and  output looks like this

 

Artist List

Advertisements

Consuming Webservices & Parsing JSON Response Tutorial :Part 1

Hi Folks ,

Today, I want to make a demonstration of fetching data from web servers by using NSURLConnection on objective-c platform.

What we are going to do?

We are going to create an application that will demonstrate you guys to make a GET  request with NSURLConnection. After that, the retrieved data will be shown in UiTableview .It would be basically my favorite Artist name and his image .

For this tutorial i am going to consume one WCF web service ,thanks to one of my colleague to helping me 🙂

API :http://182.72.47.242:49/RpManageCommon/GetArtistPhotos

Retrieved Data would be JSON format shown as below:

{"list":[{"image":"http:\/\/182.72.47.242:49\/images\/dy.png","name":"Dy"},{"image":"http:\/\/182.72.47.242:49\/images\/eminem.png","name":"Eminem"},{"image":"http:\/\/182.72.47.242:49\/images\/enrique.png","name":"Enrique"},{"image":"http:\/\/182.72.47.242:49\/images\/fiftycent.png","name":"Fiftycent"},{"image":"http:\/\/182.72.47.242:49\/images\/pitbull.png","name":"Pitbull"}]}

Now first of all create a new project on Xcode as a single view application. You may use any other of them however the project that I have started with was single view application.

Put UiTableView onto a xib, and make the bindings related to the view controller’s header file.

Open your view controller’s header class. In my example it is called “ViewController.h” and modify it as like as below.

import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

{

NSMutableData *receivedData;

}

@property (nonatomic, assign) IBOutlet UITableView *myTableView;

-(void)connectWebserviceSync;

@end

What we have done in here, we have created UITableView, and 1 NSMutableData object. One of the most important thing in here is that our view controller has implemented NSURLConnectionDataDelegate. Whenever our connection object start to fetching from a web page, if the delegate of our connection object is set to this view controller, it will call delegate methods to warn our view controller about the state of connection. Now let’s make some coding over view controller’s .m file.

First of all, I would like to implement the connectWebServiceSync method. Whenever  application will enter in ViewWillAppear Mode  it will call connectWebServiceSync method.

connectWebServiceSync  simply create NSURLConnection request and execute it.

Modify your .m as shown below

-(void)viewWillAppear:(BOOL)animated

{

//call webservice here

[self connectWebserviceSync];

}

-(void)connectWebserviceSync

{

// Create the request.

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@”http://182.72.47.242:49/RpManageCommon/GetArtistPhotos”%5D

cachePolicy:NSURLRequestUseProtocolCachePolicy

timeoutInterval:60.0];

// create the connection with the request

// and start loading the data

NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

if (theConnection) {

// Create the NSMutableData to hold the received data.

// receivedData is an instance variable declared elsewhere.

receivedData = [[NSMutableData data] retain];

} else {

// Inform the user that the connection failed.

NSLog(@”connection failed”);

}

}

Here I create url, and afterwards a request with respect to instance of url. These are the same procedures for every requests

The tricky part , the delegation, comes into play at this time. The folks at Apple has created a simple way to deal with the states of connection by using delegation structure.There are actually lots of delegate methods in NSURLConnectionDataDelegate however, just only 3 of them is required to be implemented in class. Those are;

this method might be calling more than one times according to incoming data size

*/
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[receivedData appendData:data];
}
/*
if there is an error occured, this method will be called by connection
*/
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@”%@” , error);
}
/*
if data is successfully received, this method will be called by connection
*/
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
 NSString *responseString = [[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding] autorelease];   NSLog(@”Succeeded! Received JSON String %@ “,responseString);
// release the connection, and the data object

    [connection release];

[receivedData release];

}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data this method is called more than ones if the data returned by server is huge. NSURLConnection is clever enough how to split and whenever it gets any kind of data it calls this method from bound delegate class.

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error this method is called if something is abnormally going on during the connection.

-(void)connectionDidFinishLoading:(NSURLConnection *)connection this method is called when connection finishes its job successfully. All the actions after fetching data from server can be done here. In our example, we have filled our data into our object “receivedData”. Now that, we can  convert our data into string with UTF8 encoding, and then can store it somewhere or Log it.

For this tutorial i just used NSLog to print json response.If you are implementing above code hit run and look into your console for output.

webservicedemo

What to do next?

We have Raw JSON string as a response.now we have to parse that raw JSON response and populate data over UITableView view

to be continued…..

UITableView Tutorial Part 3: ENABLING & CONFIGURING EDIT MODE

Hi Folks,

Hopes you are enjoying your weekend…

This is another tutorial related to UITableView,previously we have learned

1.Creating and using Simple tableView and populated data.

2. Creating UITableView using xib.

You can check Part 1 here and Part 2 here.

Some time you need to Edit your table view according to app .Let’s say you are dealing with some Music Player App, user must be able to delete songs from the list and thus UITableView requires Editing of Cells.

If you’re presenting data to your users in a tableView, it is very likely you would want to add & remove rows from the table. In order to do this, UITableViews have a BOOL property called isEditing, which you can use to enter & exit edit mode.

Edit Mode on a UITableView is configured through the

– (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath*)indexPath

and

– (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath

Swipe-to-delete will be enabled by default if a tableView can be edited.

methods of the UITableView DataSource Protocol.Add these two method to part 2 tutorial source code.

Enabling Edit Mode

Return YES for all IndexPath Sections / Rows you want Edit Mode enabled for.

– (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath*)indexPath

{

// Return YES

returnYES;

}

Configuring Edit Mode – The TableView:

The following code will affect how  existing ones deleted.

– (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath

{

if (editingStyle == UITableViewCellEditingStyleDelete) {

// Delete the row from the data source

[items removeObjectAtIndex:indexPath.row];

//reload Table view

[tableView reloadData];

}

Now hit run and swipe to delete the cell

Screen Shot 2013-01-27 at 3.10.01 PM

Screen Shot 2013-01-27 at 3.10.22 PMDone…Enjoy coding.. stay tune for more tutorial

UITableView Tutorial Part 2: Customizing Table View

Hi Folks,

Hope you have enjoyed my previous tutorial if not ,go and explore it here

This second part of UITableView tutorial is all about customizing Table View  using xib.Creating your own tableview cell could be such a hassle when you do it programmatically. To be able to follow this tutorial, you need to know how to add a tableview first. Refer to the previous tutorial on how to add a tableview if you still don’t know how to add it yet.

Let’s start!

1. Add a new file of subclass UITableViewCell.

UITableViewCell

2. After adding a new UITableViewCell class, only .h and .m files are created. So, let’s add another file, an empty Interface Builder Document (xib file). Name it with the same name with our .h and .m files (to avoid confusion).

choose templates

3. Drag a tableview cell to your xib file, and change its class to SampleTableCell (the one we added a while ago).

CustomClass

4. Start customizing your cell. Here in my example, I want to make a Top Artist Cell (One with profile pictures, & name)

    1. I changed the height of my cell to 90 (instead of the default cell height which is 44).
    2.  I added a UIImageView for the profile pictures.
    3. Added a UILabel for the name.

5. Make an IBOutlet property of the objects that might change dynamically. In our example, our profilePicture object may change dynamically, depends on who is on Top Artist Chart.  And remember to synthesize these objects.
//Inside .h file

@property (nonatomic, assign) IBOutlet UIImageView *picture;
@property (nonatomic, assign) IBOutlet UILabel *name;

//Inside .m file

@synthesize picture;
@synthesize name;
6. Connect these outlets to your objects in your xib file.

7. Create a new File, subclass of NSObject. This file will serve as our “Artist” object. This class must hold the important information we need, like the profilePicture filename, Name.
//Artist.h file

@interface Artist : NSObject
@property (nonatomic, strong) NSString *artistName;
@property (nonatomic, strong) NSString *imageName;
@end
//Artist.m file
@implementation User
@synthesize artistName;
@synthesize imageName;
@end

8. Create your Artist objects and put them all in your items Array.
//I created five Artist. Sample code…

    Artist *artist1 = [[Artist alloc] init];
    artist.artistName=@”Eminem”;
artist.imageName=@”eminem.png”;

//Put them all in our array list
items = [[NSArray alloc] initWithObjects: artist1, artist2, artist3, artist4, artist5, nil];
9. Before we proceed, change the cell’s Identifier . We need it later.One more thing add some Artist images in project

cell identifier

Remember the Datasource and Delegate methods of our tableView from the previous tutorial? We are going to modify/add some methods.

10. Remember that our customized cell’s height was changed to 90, right? It has become taller than the usual height of our tableViewCell. Add this method so that our tableView will know that the cell’s height was changed.
//If we did not change the height of our cell, we do not need to add this method.

– (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 90.0;
}

11. Lastly, modify this method cellForRow. This is the part where we tell the tableView that we will use our custom cell.

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @”ArtistCell”;
    SampleTableCell *cell = (SampleTableCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray* topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@”SampleTableCell” owner:self options:nil];
        for (id currentObject in topLevelObjects) {
            if ([currentObject isKindOfClass:[UITableViewCell class]]) {
                cell = (SampleTableCell *)currentObject;
                break;
            }
        }
    }
    // Configure the cell.

    Artist *artist = [items objectAtIndex:indexPath.row];

cell.picture.image= [UIImage imageNamed:artist.imageName];

cell.name.text = artist.artistName;

cell.selectionStyle = UITableViewCellSelectionStyleNone;

return cell;

}

12. Hit Run! check output as shown below

Runenjoy coding….stay tune

UITableView Tutorial Part 1: Introduction to iPhone TableView

Hi fellas

This 3 Part of UITableView Tutorial will take you that level where you can able to deal with creating,customizing, modifying ,Binding data and much more to the iPhone TableView.

So Let’s start..

Table view is commonly used to show lists of data. A table view is the view object that displays table’s data and instance of UITableView. Each visible row in a table view is implemented by UITableViewCell. Table views are not responsible for storing your table’s data. They store only enough data to draw the rows that are currently visible. Table views get their configuration data from an object that conforms to the UITableViewDelegate protocol and their row data from an object that conforms to the UITableViewDataSource protocol.

Follow the steps below to create UITableView sample:

1.Open Xcode and create new view based project named ‘MyTable’

2.Modify code in the MyFirstTableViewController.h file as follow:

 

#import <UIKit/UIKit.h>

@interface MyFirstTableViewController : UIViewController

<UITableViewDelegate,UITableViewDataSource>{

NSArray *listData;

}

@property(nonatomic, retain) NSArray *listData;

@end

3.Open MyFirstTableViewController.xib file and drag Table View from Library over to the View Window.

4.Connect tableview’s dataSource and delegate from connection inspector to File’s Owner.

5.Modify code in the MyFirstTableViewController.m file as follow:

 

#import “MyFirstTableViewController.h”

@implementation MyFirstTableViewController

@synthesize listData;

– (void)viewDidLoad {

NSArray *array = [[NSArray alloc] initWithObjects:@”iPhone”, @”iPod”,

@”iPad”,nil];

self.listData = array;

[array release];

[super viewDidLoad];

}

– (void)dealloc {

[listData dealloc];

[super dealloc];

}

#pragma mark –

#pragma mark Table View Data Source Methods

– (NSInteger)tableView:(UITableView *)tableView

numberOfRowsInSection:(NSInteger)section

{

return [self.listData count];

}

– (UITableViewCell *)tableView:(UITableView *)tableView

cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

static NSString *SimpleTableIdentifier = @”SimpleTableIdentifier”;

UITableViewCell *cell = [tableView

dequeueReusableCellWithIdentifier:SimpleTableIdentifier];

if (cell == nil) {

cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault

reuseIdentifier:SimpleTableIdentifier] autorelease];

}

NSUInteger row = [indexPath row];

cell.textLabel.text = [listData objectAtIndex:row];

return cell;

}

@end

In viewDidLoad we are creating an array of data to pass to our Table View.
We have also added two more methods of data source delegate which are mandatory to implement when your implementing UITableViewDataSource delegate.

 

(NSInteger)tableView:(UITableView *)tableView

numberOfRowsInSection:(NSInteger)section

which specifies how many number of rows are there in one section of the Table View.
The default number  of section in Table View is one.

Another method is

 

  – (UITableViewCell *)tableView:(UITableView *)tableView

cellForRowAtIndexPath:(NSIndexPath *)indexPath

Which is called by table view when it needs to draw a row. This method is called n times and value of n is equal to value returned by first method. As this method is called once for every row,

 

if (cell == nil)

checks, if cell exits before, if not create new cell. Here ‘indexPath’ parameter gives us current Indexpath of the row from which we can get the current drawing row. Then we set the text of textLabel property of the current drawing cell and finally return the cell to the Table View.

 

Output will look like this:

uitableview

HelloWorld iOS application

Hi folks,

This is very first post about iPhone app development .

I assume you people are familiar with basic of objective c and cocoa framework and Xcode.

So this post bring you the anatomy of first HelloWorld  application

let’s start…

Prerequisites

1. Xcode

2.basic of  objective c and iphone SDK

last and foremost  patience 🙂

Here are the following steps you need to build your HelloWorld application

1.Create new XCode Project

  Create your  project going through XCode ->File ->New Project and select  Empty Application .Name the project HelloWorld and click Save as shown in figure

XCode will create two file AppDelegate.h and AppDelegate.m . Difference between .h and .m file is in objective c all declaration goes to  .h file and implementation goes to .m file.

Now What  is AppDelegate  actually?

When you create your  project, main.m file under  Supporting files is generated by XCode

it looks like

#import <UIKit/UIKit.h>

int main(int argc, char *argv[])

{

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    int retVal = UIApplicationMain(argc, argv, nil, nil);

    [pool release];

    return retVal;

}

 as in any C program the execution of Objective -c application starts from main().the main() function starts by creating autorelease pool and ends by releasing it. In between it makes a call to the UiApplicationMain() function. UiApplicationMain() is declared as follows

int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);

The UiApplicationMain() instantiate the application and the application delegate objects. after that,it sets the delegate property of the application object to the application delegate instance.

The Typical application delegate class looks like

#import <UIKit/UIKit.h>

@interface AppDelegate : NSObject <UIApplicationDelegate>

{}

@end

Notice that application delegate class inherits NSObject class and adopts UIApplicationDelegate protocol and implements the UIApplicationDelegate methods.One of the very first  method of UiApplicationDelegate is

 – (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{}

This method is starting point for developer didFinishLaunchinWithOptions is application life cycle method it is called when application will launch (onCreate() in Android )

Note : NSObject is the super class of all classes available in objective c and Protocol is  here interface 

 – (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

    // Override point for customization after application launch.

    self.window.backgroundColor = [UIColor whiteColor];

    [self.window makeKeyAndVisible];

    return YES;

}

 above code simply illustrate that when application will launch  a new window will be allocated by

self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
and  set its background color to white by
self.window.backgroundColor = [UIColor whiteColor];
at last make it visible.

 2. Create User Interface using code 

 For your application very first object you need is appdelegate class which we have been seen above

now suppose you application has more than one screen so how will you create your screen(View)?

In iphone each screen is   ViewController (in Android Activity).

For this create a simple class which is a subclass of UIViewController going through

right click on AppDelegate.h  >>>newFile  >>Cocoa Touch >> UiViewController subclass >>next.

Name the file  and create it.

 3. Create object of your newly created UIViewController and add it to the main Window.

 modify AppDelegate.h file with following piece of code

#import <UIKit/UIKit.h>

#import “HelloWorldViewController.h”

 @interface AppDelegate : UIResponder <UIApplicationDelegate>

{

    HelloWorldViewController *helloWorldVC;

}

@property (strong, nonatomic) UIWindow *window;

@end

modify AppDelegate.m file
– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

    // create viewcontroller object

    helloWorldVC=[[HelloWorldViewController alloc]init];

   //add it to the window

    [self.window addSubview:helloWorldVC.view];

    [self.window makeKeyAndVisible];

    return YES;

}

what you have done so far is you have created  HelloWorldViewController and added it to main window. now create label in your controller

4.Create UiLabel and add it to HelloWorldViewController
  •  Open HelloWorldViewController.h file and declare UILabel
#import <UIKit/UIKit.h>
@interface HelloWorldViewController : UIViewController
{

    UILabel *label;

}

@end
  •  Open HelloWorldViewController.m file create label and set it’s property

#import “HelloWorldViewController.h”

 @implementation HelloWorldViewController

– (id)init

{

    self = [super init];

    if (self) {

        label=[[UILabel alloc]initWithFrame:CGRectMake(100, 250, 200, 30)];

        label.text=@”HelloWorld”;

    }

    return self;

}

  •  Add label to ViewController

-(void)loadView

{

    [super loadView];

    [self.view addSubview:label];

}

5. Build and Run

Run your project by clicking run button (top left corner in XCode).

 enjoy coding……

Feel free to comment .For any query mail me @ bpsingh@pmtsl.onmicrosoft.com