How to record audio using AVAudioRecorder in iPhone application?

This post deals with recording sound in iPhone application using AVAudioRecorder class. AVAudioRecorder is simple to use and provides facilities for pausing/resuming recording and handling audio interruptions.

Suppose we have a view controller file “RecordViewController”

Implement the following code in RecordViewController.h file.

 

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

@interface RecordViewController : UIViewController<AVAudioRecorderDelegate> {
	NSURL *SoundPath;
	IBOutlet UIButton *recordOrStopButton;
	bool recording;
	AVAudioRecorder *soundRecorder;

}
@property(nonatomic,retain) NSURL *SoundPath;
@property(nonatomic,retain) AVAudioRecorder *soundRecorder;
- (IBAction) recordOrStop: (id) sender;
-(IBAction)play;
@end

In the above code

a) We have added AVFoundation framework from the list of existing frameworks and imported AVFoundation.h  to RecordViewController.h file.

b) We have also made this class as the delegate for AVAudioRecorder by implementing AVAudioRecorderDelegate.

Now come to RecordViewController.xib file, add two buttons from the library  and make connections as shown in figure.

 

 

Now come to RecordViewController.m file and write following code as shown.

@synthesize SoundPath,soundRecorder;

 

- (void)viewDidLoad {
    [super viewDidLoad];
	NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDir =[paths objectAtIndex:0];
    NSString *soundFilePath =[documentsDir stringByAppendingPathComponent:@"mysound.caf"];
	NSURL *newURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
	self.SoundPath=newURL;
	[newURL release];
	recording = NO;
	}

In the above code we are specifying the path for saving the recorded audio. The audio will be saved in Documents folder of this application. Initially we set recoding to NO.

-(IBAction)play
{
	AVAudioPlayer *player =[[AVAudioPlayer alloc] initWithContentsOfURL:SoundPath error: nil];

	[player prepareToPlay];
	[player play];

}

We have implemented this method for playing the recorded audio using AVAudioPlayer.

- (IBAction) recordOrStop: (id) sender {
	if (recording) {
		[soundRecorder stop];
		recording = NO;
		self.soundRecorder = nil;
		[recordOrStopButton setTitle: @"Record" forState:UIControlStateNormal];
		[recordOrStopButton setTitle: @"Record" forState:UIControlStateHighlighted];
		[[AVAudioSession sharedInstance] setActive: NO error: nil];
		[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
		[[AVAudioSession sharedInstance] setActive: YES error: nil];
		} else {
		[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryRecord error: nil];
		[[AVAudioSession sharedInstance] setActive: YES error: nil];
		NSDictionary *recordSettings =[[NSDictionary alloc] initWithObjectsAndKeys:
		 [NSNumber numberWithFloat: 44100.0], AVSampleRateKey,
		 [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
		 [NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
		 [NSNumber numberWithInt: AVAudioQualityMax], AVEncoderAudioQualityKey, nil];
		AVAudioRecorder *newRecorder =[[AVAudioRecorder alloc] initWithURL: SoundPath settings: recordSettings error: nil];
		[recordSettings release];
		self.soundRecorder = newRecorder;
		[newRecorder release];
	    soundRecorder.delegate = self;
		[soundRecorder prepareToRecord];
		[soundRecorder record];
		[recordOrStopButton setTitle: @"Stop" forState: UIControlStateNormal];
		[recordOrStopButton setTitle: @"Stop" forState: UIControlStateHighlighted];
		recording = YES;
		}
	}

In the above code we set the category of AVAudioSession to”AVAudioSessionCategoryRecord” and activate it. After that in recordSettings dictionary object we store the values for various settings. The AVAudioRecorder object is then allocated with these settings, after that we start recording.

For playing recorded sound we stop the recording and change the category of AVAudioSession to AVAudioSessionCategoryPlayback and activate it. Recorded audio is listened with the help of AVAudioPlayer object.

 -(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
	NSLog(@"success");
}
-(void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error
{
	NSLog(@"fail");
}

We can also implement the above delegate methods which are called when audio is recorded successfully or when it fails.

Save, Build and run you project

NOTE- For recording of sound we need actual device i.e iPhone, it will not work on Simulator.

How to play sound in iPhone application?

This post deals with playing sound in iPhone applications. You can play sounds in your application using an instance of AVAudioPlayer class. AVAudioPlayer lets you play audio in different formats available in iOS. You can play, pause or stop an audio player using its properties.

1) Add the framework AVFoundation.framework from existing framework.

2) Lets say we have a view controller class “PlayViewController” . In .h file write the following code as shown below.

#import <UIKit/UIKit.h>

#import <AVFoundation/AVAudioPlayer.h>
@interface PlayViewController : UIViewController<AVAudioPlayerDelegate> {
	AVAudioPlayer *player;
	IBOutlet UIButton *button;
}

-(IBAction)play;
@end

3) In the above code we have imported “AVAudioPlayer.h” which is inside AVFoundation framework. We have also implemented AVAudioPlayerDelegate protocol in this class.

4) Now come to .m file and write the following code in “viewDidLoad” method.

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: @"snd1" ofType: @"mp3"];
 NSURL *fileurl = [[NSURL alloc] initFileURLWithPath: soundFilePath];
 player =[[AVAudioPlayer alloc] initWithContentsOfURL: fileurl error: nil];
 [fileurl release];
 [player prepareToPlay];
 [player setDelegate: self];

Here snd1 is the name of the mp3 file present in the resources folder of the Xcode project.

5) Implement the play method as shown below.

-(IBAction)play
{
	if (player.playing) {
		[button setTitle: @"Play" forState: UIControlStateHighlighted];
		[button setTitle: @"Play" forState: UIControlStateNormal];
		[player pause];
		}
	else {
		[button setTitle: @"Pause" forState: UIControlStateHighlighted];
		[button setTitle: @"Pause" forState: UIControlStateNormal];
		[player play];
		}
}

Here property playing of player tells whether the player is currently playing or not, based on which we set the title for button.

6) Implement the following delegate method, as shown, in .m file

- (void) audioPlayerDidFinishPlaying: (AVAudioPlayer *) player successfully: (BOOL) completed {
	if (completed == YES) {
		[button setTitle: @"Play" forState: UIControlStateNormal];
        }
	}

This delegate method is called when the player is finished playing. We can change title of the button inside the implementaion of the above method.

7) Now open .xib file, add a UIButton and make connections as shown below.

8) Save, build and run your application.

 

 

 

How to use UIWebView in iPhone?

This post deals with using UIWebView in iPhone applications. You can use webview to load web contents in your application.

1) Lets say we have a view controller class “webViewController”. Open webViewController.h file and add the following lines of code.

#import <UIKit/UIKit.h>
@interface webViewController : UIViewController {
	IBOutlet UIWebView *WView;
}

@end

2) Now come to webViewController .m file and add the following lines of code in “viewDidLoad” method.

NSURL *URL = [NSURL URLWithString:@"http://www.google.com"];

	NSURLRequest *requestObj = [NSURLRequest requestWithURL:URL];

	[WView loadRequest:requestObj];

3) As we will be making this class as the delegate for UIWebView so add the delegate method, as shown below, which is called when UIWebView finishes loading of content.

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
	NSLog(@"finished download");
}

4) Now open webViewController.xib for adding objects to view and making connections as shown in figure below.

In the above xib we have added

a) A UIWebView which will show the web content.

b) 4 Buttons

(i) Back- for moving back to previous page in back-forward list. Connected to action “goBack” of UIWebView as shown.

(ii) Forward- for moving to next page in back-forward list. Connected to action “goForward” of UIWebView as shown.

(iii) Stop- to stop loading of request. Connected to action “stopLoading” of UIWebView as shown.

(iv) Reload- to reload the request. Connected to action “reload” of UIWebView as shown.

c) A Label saying “How to use UIWebView” which you may or may not add.

5) Connect the outlet WView to UIWebView. Also make the class as a delegate for UIWebView by making connection between delegate and File’s Owner.

6) Save, Build and Run the Project.

7) Output is as shown below.

How to detect shakes in an iPhone Application?

This post deals with detecting shakes in an iPhone application. The shake API has 3 events which can be handled in your code

a) motionBegan:

b) motionEnded:

c) motionCancelled:

Now lets see how you can code these events in your application

1)Open Xcode, make a view based application and name it as shake.

2)Open shakeViewController.xib and populate it with a TextField and a UIDatePicker as shown below

3) Now open shakeViewController.h file. Add the following highlighted code

 

#import <UIKit/UIKit.h>
@interface ShakeViewController : UIViewController {
IBOutlet UITextField *textField;
IBOutlet UIDatePicker *datePicker;
}
@property (nonatomic, retain) UITextField *textField;
 @property (nonatomic, retain) UIDatePicker *datePicker;
-(IBAction) doneEditing: (id) sender;
@end

 

4) In the Interface Builder make the connections for textField and datePicker

5) Right click the textField and connect its Did End On Exit event to doneEditing: method as shown below

 

 

6) Now write the following highlighted code in the shakeViewController.m file

 

#import "ShakeViewController.h"
@implementation ShakeViewController
@synthesize textField, datePicker;
-(void) viewDidAppear:(BOOL)animated
{
[self.view becomeFirstResponder];
 [super viewDidAppear:animated];
}
-(IBAction) doneEditing: (id) sender
{
 [self.view becomeFirstResponder];
}
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (event.subtype == UIEventSubtypeMotionShake )
 {
NSLog(@"motionBegan:");
}
}
-(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
 if (event.subtype == UIEventSubtypeMotionShake )
{
NSLog(@"motionCancelled:");
}
}
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
 {
 if (event.subtype == UIEventSubtypeMotionShake )
{
NSLog(@"motionEnded:");
}
}
-(void)dealloc
{
[textField release];
 [datePicker release];
[super dealloc];
}

 

7) Right click the classes group and choose add new file. Select the UIView subclass template.

 

8) Name the file as ShakeView.

9) Open ShakeView.m and add the following method

-(BOOL)canBecomeFirstResponder
{
 return YES;
}

 

10) In Interface Builder, select the View window and view its Identity Inspector window. Select its class name as ShakeView.

 

11) Save everything and then run the application.

12) To simulate shaking on simulator choose Hardware->Shake Gesture

13) Observe the console.

Note: You should have first responder in your view to fire the events. So we have set view to first responder in viewDidAppear: and then again when keyboard is dismissed we make view as first responder in doneEditing: method. By default your view will never be first responder so you will have to override the default canBecomeFirstResponder method to return a YES:

 

How to implement searching in UITableView

How to implement searching in UITableView

 

So, today we are going to see how to  implement Searching of data in UITableView.
Given below is the snapshot of what will our app look like.

iPhone Application Development

So lets get started :-


1.) Creating a new project

The first step is to create a new project. For this we need to :-

a.) launch Xcode.
b.) click on File -> New Project.
c.) select Application (under iOS).
d.) select View-Based Application project template.
e.) Under Product , choose iPad.
f.) click on choose.
g.) save the project and  name it “search”.

iPhone Application Development

This is how the list of files look like in Xcode.

iPhone Application Development

2.)Building the Interface


Go to “Resources” folder and click “searchViewController.xib” file. This will launch the “Interface Builder” which consists of few windows.

a.)Now we will go to the “Library window” and from there we will select the “Search Bar” and “Table View” drag it to the “View window”.
b.) We will make the interface as shown in the figure and name the objects according to it.

iPhone Application Development

3.)Writing Code

a.)So Code for “searchViewController.h” file


There would be a piece of code that Xcode has already written for you. Here’s what the whole code will look like.

#import <UIKit/UIKit.h>

@interface searchViewController : UIViewController
<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>{
	NSMutableArray *listOfItems;
	UITableView *tableView;
	IBOutlet UISearchBar *sBar;
	NSMutableArray *copyListOfItems;
	BOOL searching;

}
@property(nonatomic,retain)UITableView *tableView;
-(void) searchTableView;
- (void) doneSearching_Clicked:(id)sender;

@end

Here  we have  the delegates for the UUISearchBar, TableView and TableViewDataSource.

We  also declare a TableView object, a SearchBar object and few other objects which needs will be explained in the next step.

We declare two methods “searchTableView” and “doneSearching_Clicked” which will be called for searching and end searching respectively.

 

b.)Code for “searchViewController.m” file

 

In this part we synthesize the “tableView” object and in “viewDidLoad” method we allocate the objects to the “MutuableArray”.

We implement the methods “searchBarDidBeginEditing” and “doneSearching_Clicked”.

Here we allocate the number of sections and number of rows in the TableView.

In “searchTableView” object we implement the logic for search.

We define a temporary string that contains the string entered in the “SearchBar”.

Then  this  string is matched with the objects of the array in the “TableView” and the results are  stored in another array “copyListOfItems” and is displayed.

4.)Building the Connections

#import "searchViewController.h"

@implementation searchViewController
@synthesize tableView;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"Countries";
	listOfItems = [[NSMutableArray alloc] initWithObjects:@"Iceland", @"Greenland", @"Switzerland", @"Norway",@"Sri Lanka",@"China", @"New Zealand", @"Greece", @"Rome", @"Ireland",@"India", @"U.S.A", nil];

	//Initialize the copy array.
	copyListOfItems = [[NSMutableArray alloc] init];

	//Set the title
	self.navigationItem.title = @"Countries";
    searching = NO;
	sBar.autocorrectionType = UITextAutocorrectionTypeNo;
}
- (void) searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar {

	searching = YES;
	self.tableView.scrollEnabled = NO;

		}

- (void) doneSearching_Clicked:(id)sender {

	[sBar resignFirstResponder];

	self.navigationItem.rightBarButtonItem = nil;
	self.tableView.scrollEnabled = YES;

}

- (NSIndexPath *)tableView : (UITableView *)theTableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {

	return indexPath;

}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {

	//Remove all objects first.
	[copyListOfItems removeAllObjects];

	if([searchText length] > 0) {

		[self searchTableView];

	}
	else{
		searching=NO;

	}
	[self.tableView reloadData];

}

- (void) searchTableView {

	searching = YES;
	NSString *searchText = sBar.text;
	NSMutableArray *searchArray = [[NSMutableArray alloc] init];

	[searchArray addObjectsFromArray:listOfItems];

	for (NSString *sTemp in searchArray)
	{
		NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];

		if (titleResultsRange.length > 0)
			[copyListOfItems addObject:sTemp];
	}

	[searchArray release];
	searchArray = nil;
}

#pragma mark -
#pragma mark Table view data source

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

	return 1;

}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

	if (searching)
		return [copyListOfItems count];
	else {
		return [listOfItems count];
	}
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

	static NSString *CellIdentifier = @"Cell";

	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
	}

	// Set up the cell...

	if(searching)
		cell.textLabel.text = [copyListOfItems objectAtIndex:indexPath.row];
		else {

			//First get the dictionary object

			cell.textLabel.text = [listOfItems objectAtIndex:indexPath.row];
		}

	return cell;
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

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

- (void)viewDidUnload {
}

- (void)dealloc {
	[sBar release];
	[tableView release];
	[listOfItems release];
    [super dealloc];
}

@end

Our next step is to build the connections between the code we have written with our Interface elements.

a.)So we click on the “searchViewController.xib” in the “Resources” folder to launch “Interface Builder.

b.)There in the “Document window” we select “File’s Owner” and right click it.

c.)Now a window pops up which shows all the “Outlets and Actions” defined by us.

d.)Do the connections as shown below.

iPhone Application Development

5.)Build and Run

iPhone Application Development
Now finally we have to go to the Xcode and there at the top bar we see “Build and Run”. Just click it to run the application. Make sure we have saved our application before doing this.

So finally our app will look something like this:-

iPhone Application Development

 

How to detect touches in iPhone/iPad application programming?

This post deals with detecting multi-touches on iPhone screen.

One of the most important feature of iPhone is its touchscreen which can detect multiple touches. This feature allows most natural interaction with objects visible on iPhone screen.

Lets start

1) Create a new view based application and name it Multi-Touch.
2)Drag and drop an image into resource folder. Lets say the name of image is apple.jpeg.

 

3) Open MultiTouchViewController.xib file

4) Populate the view with ImageView. Ensure that ImageView covers the entire view.

5) Select image property on the ImageView to apple.jpeg in its Attribute window.

6) Open MultiTouchViewController.h and write the following highlighted code

 

7) Drag the File’s Owner item to the ImageView view. Select imageView.

8) Write the following code in MultiTouchViewController.m

 

@synthesize imageView;
//---fired when the user finger(s) touches the screen---
-(void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event {
//---get all touches on the screen---
 NSSet *allTouches = [event allTouches];
//---compare the number of touches on the screen
switch ([allTouches count]) {
//---single touch---
case 1: {
//---get info of the touch---
UITouch *touch = [[allTouches allObjects] objectAtIndex:0];
//---compare the touches---
switch ([touch tapCount]) {
//---single tap---
case 1: {
imageView.contentMode = UIViewContentModeScaleAspectFit;
}
 break;
//---double tap---
case 2: {
imageView.contentMode = UIViewContentModeCenter;
}
break;
}
}
break;
}
}

 

As we see above that we use “touchesBegan:” delegation method which is fired when user touches the screen. NSSet object allTouches tells that how many fingers are touching the screen. We extract details of the first touch by using the allObjects method of the NSSet object to return an NSArray object. The UITouch object (touch) contains the tapCount property, which tells us whether the user has single-tapped the screen or performed a double tap (or more).

9) Save and Build the application.

10) Single tap the image to enlarge it and double tap to return to its original size.

 

How to sort data and display in UITableView

How to sort data and display in UITableView

 

So,  today we are going to see how to make a simple app in iPad that will sort the list of countries in ascending or in descending order as per required.

Given below is the snapshot of what will our app look like.

iPhone Application Development

 

So lets get started :-

1.) Creating a new project


The first step is to create a new project. For this we need to :-

a.) launch Xcode.
b.) click on File -> New Project.
c.) select Application (under iOS).
d.) select View-Based Application project template.
e.) Under Product , choose iPad.
f.) click on choose.
g.) save the project and  name it “sort”.

iPhone Application Development

This is how the list of files look like in Xcode.

iPhone Application Development

2.)Building the Interface


Go to “Resources” folder and click “sortViewController.xib” file. This will launch the”Interface Builder” which consists of few windows.

a.)Now we will go to the “Library window” and from there we will select the “Table View” and drag it to the “View window”.

b.)Same way we are going to drag  ”Segmented Control”.

c.) We will make the interface as shown in the figure and name the objects according to it.

iPhone Application Development

3.)Writing Code


a.)So Code for “sortViewController.h” fil


There would be a piece of code that Xcode has already written for you. Here’s what the whole code will look like.

#import <UIKit/UIKit.h>

@interface sortViewController : UIViewController <UITableViewDataSource>{
	NSMutableArray *sortedArray;
	IBOutlet UITableView *tableView;
	IBOutlet UISegmentedControl *segmentedControl;
}
@property(nonatomic,retain) IBOutlet UISegmentedControl *segmentedControl;
@property(nonatomic,retain) IBOutlet UITableView *tableView;
-(IBAction) do_sorting;

@end

Here we declare an Mutable Array that will contain the sorted list of countries , a Table View object and Segmented Control objects.

We set the property for the  SegmentedControl and the TableView Object.
A function “do_sorting” which when called will sort the list in acending or descending as required.

Property List:

Property lists organize data into named values and lists of values using several object types. These types give you the means to produce data that is meaningfully structured, transportable, storable, and accessible, but still as efficient as possible.

We will use them here to organize the list of countries we will be sorting out.

Lets see how to create a Property List also known as plist.

a.) In Xcode, go to File.
b.) click on File -> New File.
c.) select Resources (under Mac OS X).
d.) select Property List file template.
e.) click on choose.
f.) save and  name it as “country”.

iPhone Application Development

Fill it with the name of some countries and save it in the “Resources” directory.

The plist will look something like this,

iPhone Application Development

b.)Code for “sortViewController.m” file


#import "sortViewController.h"

@implementation sortViewController
@synthesize segmentedControl;
@synthesize tableView;
-(IBAction) do_sorting{

	if (segmentedControl.selectedSegmentIndex == 1) {

		NSSortDescriptor * sortDesc = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:NO];
		[sortedArray sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
		[tableView reloadData];
	}
	else {

		NSSortDescriptor * sortDesc = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES];
		[sortedArray sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
		[tableView reloadData];
	}

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

	return @"Country";
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
	return [sortedArray count];

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

	UITableViewCell *cell = [[UITableViewCell alloc]
							 initWithStyle:UITableViewCellStyleDefault
							 reuseIdentifier:@"cell"];

	cell.textLabel.text = [sortedArray objectAtIndex:indexPath.row];

	return cell;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

	NSString *myfile = [[NSBundle mainBundle]
						pathForResource:@"country" ofType:@"plist"];
	sortedArray = [[NSMutableArray alloc]initWithContentsOfFile:myfile];

    NSSortDescriptor * sortDesc = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES];
	[sortedArray sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
    [super viewDidLoad];
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

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

@end

We synthesize the “SegmentedControl” and “TableView” object .

In the “numberOfSectionsInTableView” method we return 1 as we are having only 1 section in the Table and we set the Title for the table as “Country”.

In “viewDidLoad” method, we bundle the plist with the Array object “­­­­­­­­­sortedArray”. We then declare an object of  “NSSortDescriptor” class that is a built in class which is used for sorting.

When app is loaded, table is filled with the elements of the array “sortedArray”.

“do_sorting” method sorts the list in ascending or descending order as required by using “NSSortDescriptor” class.

 

4.)Building the Connections


Our next step is to build the connections between the code we have written with our Interface elements.

a.)So we click on the “sortViewController.xib” in the “Resources” folder to launch “Interface Builder.

b.)There in the “Document window” we select “File’s Owner” and right click it.

c.)Now a window pops up which shows all the “Outlets and Actions” defined by us.

d.)Do the connections as shown below.

iPhone Application Development

 

5.)Build and Run


Now finally we have to go to the Xcode and there at the top bar we see “Build and Run”. Just click it to run the application. Make sure we have saved our application before doing this.

iPhone Application Development

So finally our app will look something like this:-

iPhone Application Development

How to use UIPopoverController in iPad programming?

This post deals with using UIPopoverController in iPad programming..

 

UIPopoverController is an iPad specific controller. UIPopoverController is not actually a ViewController in itself but it manages the presentation of view controllers. Popovers provide a lightweight way to present or gather information from the user and are commonly used in the following situations:

 

  • To display information about an object on the screen.
  • To manage frequently accessed tools or configuration options
  • To present a list of actions to perform on objects inside one of your views
  • To present one pane from a split view controller when the device is in a portrait orientation

Now we will see how we can make a UIPopoverController as shown above

We will take two view controllers for this tutorial

The first view controller will be popoverViewController and second view controller will be popViewController

The left pane of Xcode will look something like this

Now first come to popViewController.h and write the following code as highlighted

 

 

“delegate” property  will be assigned the object of popoverViewController class. So popoverViewController object will have the implementation of “-(void) dismiss:(popViewController *) controller;”. This method will be used to dismiss UIPopoverController. Also this is the view controller class which will be presented as a popover on the press of a button.

 

Open popViewController .xib, drag a table view on it as shown below and make the UITableViewDataSource and UITableViewDelegate connections

 

 

The above popViewController’s view will be shown as a popover and will change the value of the label in popoverViewController’s view on the selection of a row.

 

Now come to popViewController.m file

 

Populate the array with three values in viewDidLoad method

 

array=[[NSArray alloc] initWithObjects:@"JOHN",@"MIAMI",@"DEAN",nil];

Now write the following delegation methods of table view

 

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

	return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

	return [array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
	}

	cell.textLabel.text=[array objectAtIndex:(indexPath.row)];
	return cell;
	}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	popoverViewController *p=(popoverViewController *)self.delegate;
	UILabel *label;
	label=p.label;

	label.text=[array objectAtIndex:indexPath.row];
	[self.delegate dismiss:self];
	NSLog(@"hello");

}

 

As we can see from the above code that the popover, which contains the content of popViewController class, will be containing three rows. Property delegate references popoverViewController object because it acts as the delegate for popViewController and implements “-(void) dismiss:(popViewController *) controller;” method as said above. This method will contain the code to dismiss the popover. So on selection of row, the value of the label in popoverViewController will be changed to the row’s value and popover will be dismissed.

 

Now come to popoverViewController.h file and write the following highlighted code

 

As this class acts as the delegate for popViewController class, so it implements popViewControllerDelegate. UIPopoverController’s object popover will be used to represent the content of popViewController class in popover style A label will be attached in popoverViewController.xib file which will change value on selection of row in popover.”pop:” method will be fired when bar button will be pressed and will show the popover.

 

Now come to popoverViewController.xib. Drag label and barbutton, and make connections as shown

 

 

Now open popoverViewController .m file

 

Implements the pop: method as shown below

 

-(IBAction)pop:(id)sender
{
	popViewController *pop=[[popViewController alloc] initWithNibName:@"popViewController" bundle:nil];
	pop.delegate=self;

	UIPopoverController* aPopover = [[UIPopoverController alloc]initWithContentViewController:pop];

	[pop release];
	self.popover = aPopover;

	self.popover.popoverContentSize=CGSizeMake(300, 500);
    [aPopover release];
	[self.popover presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

 

In the above code we made a popViewController object which will be presented in a popover style with the help of UIPopoverController object. We set the “self” object as the delegate for popViewController object. After this we set the popover size by using property “popoverContentSize”. At last we display the popover.

Implement the delegate method “-(void) dismiss:(popViewController *) controller;”

 

-(void) dismiss:(popViewController *) controller
{
	[self.popover dismissPopoverAnimated:YES];
}

The above method will dismiss the popover

Save and build the application. Output is as shown below

 

Just click some row and you will see the value of label changing

How to use UIScrollView for the contents that are larger than iPhone screen?

This post deals with using UIScrollView for the contents which are larger than iPhone Screen.

 

Scroll views have two main purposes

1)To let users drag the area of the content they want to display.

2)To let users zoom into or out of the displayed content using pinch gestures.

We are going to see both of the above functionalities in this tutorial.

Lets say we have an image waterfall-wallpaper.jpg, with a size of 1024×768, which is bigger than iPhone screen and we want to display it on screen such that every potion of image can be seen by dragging.

 

Open .xib file

Drag a UIScrollView and arrange it as shown in figure. You may add a navigation bar also. In this tutorial navigation bar is added.

 

 

 

Now come to .h file and write the following highlighted lines of code

 

Now move to .m file and write the following code in viewDidLoad method

tempScrollView.minimumZoomScale=0.5;

    tempScrollView.maximumZoomScale=6.0;
	tempScrollView.delegate=self;
    tempScrollView.contentSize=CGSizeMake(1024,768);
	UIImage *image=[UIImage imageNamed:@"waterfall-wallpaper.jpg"];
	imview=[[UIImageView alloc] initWithImage:image];
	[tempScrollView addSubview:imview];

Here maximumZoomScale and minimumZoomScale are maximum and minimun amount of zooming a user can do.

contentSize is the size of the content to be scrolled. In this exanple image size is 1024×768

 

Also add the following delegate method for pinch gestures

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView

{

    return imview;

}

Now it’s time to connect tempScrollView outlet to UIScrollView in .xib file

Connect as shown in figure.

Save and Build the application.

Now try to move the image and you will be able to see any portion of the image.

Pinching in causes the image to zoom in and pinching out causes the image to zoom out.

For those of you testing on simulator, pinching can be performed by holding the “option”  key and moving the finger on trackpad.

How to use UISegmentedControl in iPhone & iPad

UISegmentedControl in iPhone & iPad

 

So today we are going to create a simple app that is going to use UISegmentedControl . In our previous tutorials we created simple iPhone app. This time we are going to create an iPad application. The process and code is exactly same for both of these, we just need to initially select it in the Xcode.

 

Basically our app will have a menu with name of some colors written on each menu. Whenever a menu is selected, the color of the text is changed to that represented by the menu.

Given below is the snapshot of what will our app look like.

iPhone Application Development

 

So lets get started :-

1.) Creating a new project

The first step is to create a new project. For this we need to :-

a.) launch Xcode.
b.) click on File -> New Project.
c.) select Application (under iOS).
d.) select View-Based Application project template.
e.) Under Product , choose iPad.
f.) click on choose.
g.) save the project and  name it “menu”.

 

iPhone Application Tutorial

This is how the list of files look like in Xcode.

iphone Application Development

 

2.)Building the Interface

Go to “Resources” folder and click “menuViewController.xib” file. This will launch the “Interface Builder” which consists of few windows.

a.)Now we will go to the “Library window” and from there we will select the “Text View” and drag it to the “View window”.

b.)Same way we are going to drag  ”Segmented Control” .

c.) We will make the interface as shown in the figure and name the objects according to it.

iPhone Application Development

 

3.)Writing Code

a.)So Code for “menuViewController.h” file

There would be a piece of code that Xcode has already written for you. Here’s what the whole code will look like.

#import <UIKit/UIKit.h>

@interface menuViewController : UIViewController {
	IBOutlet UISegmentedControl *mycolors;
	IBOutlet UITextView *sampleText;

}

@property(nonatomic,retain) IBOutlet UISegmentedControl *mycolors;
@property(nonatomic,retain) IBOutlet UITextView *sampleText;

-(IBAction) colorChanged;

@end

Here we declare a  “SegmentedControl” object and a “TextView” object and set their property.

We declare a function “colorChanged” which when called will change the color of the “TextView.”

 

b.)Code for “menuViewController.m” file:

#import "menuViewController.h"

@implementation menuViewController

@synthesize mycolors,sampleText;

-(IBAction) colorChanged {

if (mycolors.selectedSegmentIndex==0)
{
sampleText.textColor = [UIColor blackColor];
}
if (mycolors.selectedSegmentIndex==1)
{
sampleText.textColor = [UIColor greenColor];
}
if (mycolors.selectedSegmentIndex==2)
{
sampleText.textColor = [UIColor blueColor];
}
if (mycolors.selectedSegmentIndex==3)
{
sampleText.textColor = [UIColor brownColor];
}
if (mycolors.selectedSegmentIndex==4)
{
sampleText.textColor = [UIColor redColor];
}
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}

- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (void)dealloc {
[mycolors release];
[sampleText release];
[super dealloc];
}

@end

Here we synthesize the “mycolors” and “sampleText” objects.

Now we define the “colorChanged” method. It checks for the index value of the  “SegmentedControl” and changes the color of  “sampleText” according to it.

 

4.)Building the Connections

Our next step is to build the connections between the code we have written with our Interface elements.

a.)So we click on the “menuViewController.xib” in the “Resources” folder to launch “Interface Builder.

b.)There in the “Document window” we select “File’s Owner” and right click it.

c.)Now a window pops up which shows all the “Outlets and Actions” defined by us.

d.)Do the connections as shown below.

iPhone Application Development

 

5.)Build and Run

Now finally we have to go to the Xcode and there at the top bar we see “Build and Run”. Just click it to run the application. Make sure we have saved our application before doing this.

iPhone Application Development

So finally our app will look something like this:-

iPhone Application Development