Loading URLs from UITableView

Loading URLs from UITableView
Loading URLs from UITableView

One of the major use of UITabelView is to make menus where every cell perform a specific task or let you navigate to another view. The typical example is the Settings application we all know in iOS devices.

In this tutorial, you will see how to deal with a grouped UITableView so that each selected row leads you to a website address. All that done programmatically without relying to Interface Builder.

The source code of the project is available for download in the end of the tutorial.

Open up Xcode, File menu/New/project and choose the Single View Application template. Give it a name, and make sure Use Storyboards option is not checked, click Next and save your project.

Create empty project

For the sake of this tutorial, all your work will be in two files, ViewController.h and ViewController.m.

Open ViewController.h file in the Editor and change it to look like below:

[sourcecode language=”objc”]
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>{

NSArray *webSitesNames;
NSArray *webSitesURLs;

}

@property(nonatomic, retain)UITableView *tView;
@property(nonatomic, retain)NSString *siteUrl;

@end
[/sourcecode]

The first line,  is very important since it make your class conform to the UITableViewDelegate and UITableViewDataSource protocols. These protocols provide a set of methods in order to interact with the UITableView such as loading data and managing events like the cell selection event.

In the second line, you declared two arrays, the first one will handle the sites description which will be shown in the UITableView, displaying Google is better then displaying http://www.google.com. The second array will handle
all URLs you will need, so that when you tap on a specific cell, you will know which site shall you go to.

The next two properties are for the UITableView and the selected cell value respectively.
Now switch to the ViewController.m file. Firstly, you need to synthesize the two properties you just declared in the ViewController.h.

[sourcecode language=”objc”]
@synthesize tView;
@synthesize siteUrl;
[/sourcecode]

Later, in the viewDidLoad method, you are going to initialize the arrays that you will be using with the UITableView. Then,
you need to configure the new TableView frame, set the delegates to self and finally, add the TableView
to the main view. So change your viewDidLoad method to look like this:

[sourcecode language=”objc”]
– (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

//This array will handle all the URLs, you will refer to its content when a TableView cell is selected
webSitesURLs=[[NSArray alloc]initWithObjects:@"http://www.google.com",@"http://www.wikipedia.org",
@"http://www.apple.com",@"http://www.mashable.com",@"http://www.youtube.com",@"http://www.yahoo.com",
@"http://www.baidu.com",@"http://www.amazon.com",@"http://twitter.com",@"http://www.linkedin.com", nil];
//This array is what you TableView needs to populate its data
webSitesNames=[[NSArray alloc]initWithObjects:@"Google",@"Wikipedia",@"Apple",@"Mashable",@"Youtube",
@"Yahoo",@"Baidu",@"Amazon",@"Twitter",@"LinkedIN", nil];
//Configuring the TableView
tView=[[UITableView alloc]initWithFrame:CGRectMake(10,0,300,self.view.frame.size.height)
style:UITableViewStyleGrouped];
tView.backgroundColor=[UIColor clearColor];
//Set the delegates
tView.dataSource=self;
tView.delegate=self;
//Add to main view
[self.view addSubview:tView];
}
[/sourcecode]

In the next part, you will implement some protocols methods related to the TableView as well as
the UIAlertView that you will use to prompt the user for confirmation.

Let’s start by the UITableView datasource protocol, though you don’t need to implement all of the provided
methods, you should implement some of them in order to populate data to the UITabelView when loading.

So, place this code somewhere in ViewController.m file:

[sourcecode language=”objc”]
#pragma mark UITableView datasource

– (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

return 1;//One section for the UITAbleView

}

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

NSString *identifier=@"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

if (nil == cell){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
cell.textLabel.text=[webSitesNames objectAtIndex:indexPath.row];//assigning a value for the given cell,
this value is extracted from webSitesNames array
}
return cell;

}

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

return [webSitesURLs count];//or [webSitesNames count], since they have the same number of items

}
[/sourcecode]

You done with the datasource protocol methods, now turn to the delegate protocol. For that, you will
need to know at least which cell in the TableView was selected by the user, so you need to implement
the didSelectRowAtIndexPath delegate method as shown below:

[sourcecode language=”objc”]
#pragma mark UITableView delegate

– (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

siteUrl=[webSitesURLs objectAtIndex:indexPath.row];
[self alert:[webSitesNames objectAtIndex:indexPath.row]];

}
[/sourcecode]

The first statement in the method above will catch the value (site url) of the selected UITableView
row and assign it to the variable siteUrl. Then, you call another method that will show the alert view
to prompt for confirmation before loading the selected URL.

Go ahead and implement the alert method called above:

[sourcecode language=”objc”]
#pragma mark UIAlertView
-(void)alert:(NSString *)webSite{

UIAlertView *aView=[[UIAlertView alloc]initWithTitle:nil
message:[NSString stringWithFormat:@"Are
you sure you want to visit : %@",webSite] delegate:self cancelButtonTitle:@"
Cancel" otherButtonTitles:@"Ok", nil];

[aView show];
[aView release];

}
[/sourcecode]

Finally, when you confirm the prompt, you need to load the url, right? This is ideally done in the
UIAlertView delegate method called clickedButtonAtIndex. This method enable you to know
which button in the alert view was selected to perform the right action towards it.

Go on and add the following method to your file:

[sourcecode language=”objc”]
#pragma mark UIAlertViewDelegate
– (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

if (buttonIndex==1) {

//Ok button was selected
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:siteUrl]];//Load the url in Safari

}
}
[/sourcecode]

Build your project to ensure everything goes fine, and run it 🙂

P.S : You may notice the frequent use of #pragma mark directive. Actually, it’s pretty useful especially
when you got several method that deal with different tasks in your file. It enables you to organize your
implementation code and put titles for your code segments so that you can reper to a specific
method easily for later work. You can check that if you click on the Functions menu as shown below.
Functions menu
You can download the source code of the project here.

Feel free to leave a comment, i would love to hear your thoughts!

2 Comments

Comments are closed.