Monday 29 August 2011

MD5 Encryption for Secure Transfer of Password

This blog describes how to encrypt your data using MD5 encryption algorithm.

in .h file

- (NSString *) md5:(NSString *)str;

in your .m file import
#import <CommonCrypto/CommonDigest.h>

Write this method in your .m file:-


- (NSString *) md5:(NSString *)str
{
const char *cStr = [str UTF8String];
unsigned char result[16];
CC_MD5( cStr, strlen(cStr), result ); // This is the md5 call
return [NSString stringWithFormat:
@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
];
}

Now where ever you want to get an encrypted string do

NSString *md5String=[self md5:@"test"];
NSLog(@"md5String%@",md5String);

On console you will got md5String098f6bcd4621d373cade4e832627b4f6

Integration and Customization of Coverflow Library

This blog describe how to integrate cover flow effect in application using open source library .

First get the source code for CoverFlow from this link:-https://github.com/thefaj/OpenFlow

1.)Open your project and all the files in your project.
2.)Add QuartzCore and CoreGraphics Frameworks.
3.)In your View Controller.h file
import - #import "AFOpenFlowView.h"
@interface AFOpenFlowViewController : UIViewController <AFOpenFlowViewDataSource, AFOpenFlowViewDelegate>

In .m file

in viewDidLoad method do

-(void)viewDidLoad
{
NSString *imageName;
for (int i=0; i < 30; i++) {
imageName = [[NSString alloc] initWithFormat:@"%d.jpg", i];
[(AFOpenFlowView *)self.view setImage:[UIImage imageNamed:imageName] forIndex:i];
[imageName release];
}
[(AFOpenFlowView *)self.view setNumberOfImages:30];
}
add these methods:-

- (UIImage *)defaultImage {
return [UIImage imageNamed:@"transparentdefault.png"];
}

- (void)openFlowView:(AFOpenFlowView *)openFlowView selectionDidChange:(int)index {
NSLog(@"Cover Flow selection did change to %d", index);

}

Customization of Cover Flow Effect:-

In AFItemView.m file you will see this method:-

if (self = [super initWithFrame:frame]) {
self.opaque = YES;
self.backgroundColor = NULL;
verticalPosition = 0;
horizontalPosition = 0;

// Image View
imageView = [[UIImageView alloc] initWithFrame:frame];
imageView.opaque = YES;
[self addSubview:imageView];
}
Now suppose you want a white frame outside your image so for that what you have to do is:-

Then write this:-

if (self = [super initWithFrame:frame]) {
self.opaque = YES;
self.backgroundColor = NULL;
verticalPosition = 0;
horizontalPosition = 0;

// Image View
imageView = [[UIImageView alloc] initWithFrame:frame];
imageView.opaque = YES;
[self addSubview:imageView];

UIView* customView=[[UIView alloc]initWithFrame:CGRectMake(0, 220, 265, 20)];
customView.backgroundColor=[UIColor whiteColor];
customView.tag=22;
[self addSubview:customView];
[customView release];

UIView* customView2=[[UIView alloc]initWithFrame:CGRectMake(0, 20, 265, 7)];
customView2.backgroundColor=[UIColor whiteColor];
[self addSubview:customView2];
[customView2 release];

UIView* customView3=[[UIView alloc]initWithFrame:CGRectMake(0, 20, 8, 220)];
customView3.backgroundColor=[UIColor whiteColor];
[self addSubview:customView3];
[customView3 release];

UIView* customView4=[[UIView alloc]initWithFrame:CGRectMake(265, 20, 8, 220)];
customView4.backgroundColor=[UIColor whiteColor];
[self addSubview:customView4];
[customView4 release];
}

add this code in your this method

REMOVING IMAGE REFLECTION EFFECT:-

in OpenFlowView.m file

- (void)setImage:(UIImage *)image forIndex:(int)index {
// Create a reflection for this image.
//UIImage *imageWithReflection = [image addImageReflection:kReflectionFraction];
NSNumber *coverNumber = [NSNumber numberWithInt:index];
//[coverImages setObject:imageWithReflection forKey:coverNumber];
[coverImages setObject:image forKey:coverNumber];
[coverImageHeights setObject:[NSNumber numberWithFloat:image.size.height] forKey:coverNumber];

// If this cover is onscreen, set its image and call layoutCover.
AFItemView *aCover = (AFItemView *)[onscreenCovers objectForKey:[NSNumber numberWithInt:index]];
if (aCover) {
//[aCover setImage:imageWithReflection originalImageHeight:image.size.height reflectionFraction:kReflectionFraction];
[aCover setImage:image originalImageHeight:image.size.height reflectionFraction:kReflectionFraction];
[self layoutCover:aCover selectedCover:selectedCoverView.number animated:NO];
}
}

- (void)layoutCover:(AFItemView *)aCover selectedCover:(int)selectedIndex animated:(Boolean)animated
{

//newPosition.y = halfScreenHeight + aCover.verticalPosition; //comment this
newPosition.y = halfScreenHeight ;//add this
}

INCREASING/DECREASING IMAGE WIDTH:-

IN AFItemView.m file

- (void)setImage:(UIImage *)newImage originalImageHeight:(CGFloat)imageHeight reflectionFraction:(CGFloat)reflectionFraction {
[imageView setImage:newImage];
verticalPosition = imageHeight * reflectionFraction / 2;
originalImageHeight = imageHeight;
self.frame = CGRectMake(0, 20, newImage.size.width+40, newImage.size.height-20);//adjust coordinates yourself
}

Displaying multiple locations in MapView

This Blog describes how to show multiple locations in map view.

First you have to create an array in which multiple annotations will be saved.

In your ViewController.h file

NSMutableArray *addAnnotationsArray;
AddressAnnotation *addAnnotation;


In your ViewController.m file

addAnnotationsArray=[[NSMutableArray alloc]init];

Now initialize the for loop and and play it till how much locations you have to show on the map(In my case I have passed the count of my mapAddressArray which have the names of the locations ).
int k;
for(k=0;k<[self.mapAddressArray count];k++)
{
CLLocationCoordinate2D location;

I have called addressLocation method which returns the location coordinates of that location.


location=[self addressLocation:[self.mapAddressArray objectAtIndex:k]];

I have created seperate AddressAnnotation class and in this view controller created a object of that class and called initWithCoordinate method.

addAnnotation=[[AddressAnnotation alloc]initWithCoordinate:location];

[addAnnotation setMTitle:[self.companiesName objectAtIndex:k]];
[addAnnotation setMSubTitle:[self.mapAddressArray objectAtIndex:k]];

Add annotation to the addAnnotationsArray .

[self.addAnnotationsArray addObject:addAnnotation];

[addAnnotation release];
}

You have added the annotations in the array .Now you have to display these annotations on the map

int l;
for(l=0;l<[self.addAnnotationsArray count];l++)
{
[map addAnnotation:[self.mapAddAnnotations objectAtIndex:l]];
}

AddressLocation Method:-

-(CLLocationCoordinate2D) addressLocation:(NSString *)addrss {
NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv",
[addrss stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
NSArray *listItems = [locationString componentsSeparatedByString:@","];

double latitude = 0.0;
double longitude = 0.0;

if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:@"200"]) {
latitude = [[listItems objectAtIndex:2] doubleValue];
longitude = [[listItems objectAtIndex:3] doubleValue];
}
else {
//Show error
}
CLLocationCoordinate2D location;
location.latitude = latitude;
location.longitude = longitude;

return location;
}

AddressAnnotation.h

#import<MapKit/MapKit.h>


@interface AddressAnnotation :NSObject<MKAnnotation> {

CLLocationCoordinate2D coordinate;
NSString *mTitle;
NSString *mSubTitle;

}

@property (nonatomic, retain) NSString *mSubTitle;
@property (nonatomic, retain) NSString *mTitle;


@end


AddressAnnotation.m


#import "AddressAnnotation.h"


@implementation AddressAnnotation

@synthesize coordinate,mTitle, mSubTitle,mapId;

- (NSString *)subtitle{
return mSubTitle;
}

- (NSString *)title{
return mTitle;
}


-(id)initWithCoordinate:(CLLocationCoordinate2D) c{
coordinate=c;
//NSLog(@"%f,%f",c.latitude,c.longitude);
return self;
}



@end

How to select videos from iPhone gallery in App

When you open UIImagePickerController class object you can select only images, video files are not displayed there for selection.
This Blog describes how to select video files stored in iphone library and then do whatever as per the requirements (like playing,uploading...)
First attach MediaPlayer Framework.

In your ViewController.h file import these after attaching mediaplayer framework

#import<MobileCoreServices/UTCoreTypes.h>
#import <MediaPlayer/MediaPlayer.h>


UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
imagePicker.mediaTypes = [NSArray arrayWithObject:(NSString *)kUTTypeMovie];
NSArray *sourceTypes = [UIImagePickerController availableMediaTypesForSourceType:imagePicker.sourceType];
if (![sourceTypes containsObject:(NSString *)kUTTypeMovie ])
{
NSLog(@"no video");
}

else
{
[self presentModalViewController:imagePicker animated:YES];
}
imagePicker release];

Getting the URL of that selected video


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
if ([type isEqualToString:(NSString *)kUTTypeVideo] || [type isEqualToString:(NSString *)kUTTypeMovie])
{
NSURL *urlvideo = [info objectForKey:UIImagePickerControllerMediaURL];
}
}

Getting images and uploading it on webServer


This Blog entry describes how to open photo gallery for selecting images and uploading them on server.

UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;

If you want image to edit the image then write
imagePicker.allowsEditing = YES;

imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:imagePicker animated:YES];
[imagePicker release];

There are two methods of UIImagePickerController and this method is called when the image is selected.

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
self.image=nil;
self.image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imagedata=[NSData dataWithData:UIImagePNGRepresentation(self.image)];
NSString *base64string=[imagedata base64EncodedString];
NSString *str = [NSString stringWithFormat:testurl];
NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:base64string forKey:@"keyForUploadingImage"];
[request setRequestMethod:@"POST"];
[request setDelegate:self];
[request setDidFinishSelector:@selector(SuccessResponse:)];
[request setDidFailSelector:@selector(SuccessresponseFailed:)];
[networkQueue addOperation: request];
[networkQueue go];
[self dismissModalViewControllerAnimated:YES];
}

If u want to upload the edited image instead of original image then write:-
image = [info objectForKey:UIImagePickerControllerEditedImage];

Setting the selected image of phone in the imageView

[self.ImageView setImage:image];

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissModalViewControllerAnimated:YES];
}

Deletion of Data displaying in TableView


This blog describe an easy method to delete values showing in the list without adding some sort of buttons .

In your ViewController.h file

IBOutlet UITableView *countriesTableView;
UIBarButtonItem *donebutton;

-(void)editClicked;
-(void)doneClicked;


In your ViewController.m file

- (void)viewDidLoad {
donebutton = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(editClicked) ];
self.navigationItem.rightBarButtonItem = donebutton;
}

-(void)editClicked
{
self.countriesTableView.editing=YES;
donebutton = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleBordered target:self action:@selector(doneClicked)] ;
self.navigationItem.rightBarButtonItem = donebutton;

}

-(void)doneClicked
{
self.countriesTableView.editing=NO;
donebutton = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(editClicked) ];
self.navigationItem.rightBarButtonItem = donebutton;

}

countriesArray is my array which holds the values that will be displayed (you can write array of your own requirement)

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

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


if([self.countriesArray count]>0)
{
return [self.countriesArray count];
}
else {
return 0;
}

}

- (UITableViewCell *)tableView:(UITableView *)tbleView 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=[self.countriesArray objectAtIndex:indexPath.row];

[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}


- (UITableViewCellEditingStyle)tableView:(UITableView *)tbleView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {

if (tbleView.editing == NO || !indexPath)
return UITableViewCellEditingStyleNone;
if (tbleView.editing) {
return UITableViewCellEditingStyleDelete;
}
return UITableViewCellEditingStyleNone;
}



-(void)tableView:(UITableView *)tbleView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {
rowNo=indexPath.row;
[self.countriesArray removeObjectAtIndex:indexPath.row];
[countriesTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}


Happy Coding!!!

Rearrangement of Rows in Table View

Hi All,
This blog describes how to move table rows upwards and downwards.


First for integrating the below code you should have a table view and the delegate methods as cellforRowAtIndexPath etc.

For Rearrangement you have to copy below methods of table view

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
return YES; 
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {

NSString *stringToMove = [[self.dataArray objectAtIndex:sourceIndexPath.row] retain]; 
[self.dataArray removeObjectAtIndex:sourceIndexPath.row];
[self.dataArray insertObject:stringToMove atIndex:destinationIndexPath.row];
[stringToMove release];
[tableView reloadData];

} 
dataArray is my Array which contain the values displayed in table view

Resizing TableViewCell according to dynamic text

When there is dynamic text and we do not know how much height a label should accommodate to show the complete text usually we do trail truncation.
In this blog I have discovered how to show the dynamic text in table cell and wants to share it with all of you.

Main Logic:-

//CGSize is a variable which will contains the height of label.
CGSize labelsize;

//Label Created
UILabel *commentsTextLabel = [[UILabel alloc] init];
//text string contains the text that will be displayed in the label

NSString *text=[[self.blogTextArray objectAtIndex:indexPath.row]capitalizedString];
[commentsTextLabel setFont:[UIFont fontWithName:@"Helvetica"size:14]];

//height of the label is calculated and copied in labelsize

labelsize=[text sizeWithFont:commentsTextLabel.font constrainedToSize:CGSizeMake(268, 2000.0) lineBreakMode:UILineBreakModeWordWrap];
commentsTextLabel.frame=CGRectMake(10, 24, 268, labelsize.height);


Logic Impemented:-

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

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell=nil;
cell = [tbleView dequeueReusableCellWithIdentifier:CellIdentifier];
cell=nil;
if (cell == nil) {
cell = [self reuseTableViewCellWithIdentifier:CellIdentifier withIndexPath:indexPath];
}
if([self.blogTextArray count]>0)
{
UILabel *commentsCreatedLabel = (UILabel *)[cell.contentView viewWithTag:54];
commentsCreatedLabel.text=[self.blogTitleArray objectAtIndex:indexPath.row];
UILabel *blogDateLabel = (UILabel *)[cell.contentView viewWithTag:60];
blogDateLabel.text=[self.blogDateArray objectAtIndex:indexPath.row];
UILabel *blogTitleLabel = (UILabel *)[cell.contentView viewWithTag:50];
blogTitleLabel.text=[self.blogTextArray objectAtIndex:indexPath.row];

}
else {
}

[cell setSelectionStyle:UITableViewCellSelectionStyleNone];

return cell;
}

-(UITableViewCell *)reuseTableViewCellWithIdentifier:(NSString *)identifier withIndexPath:(NSIndexPath *)indexPath

{
UITableViewCell *cell =[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier]autorelease];
UILabel *commentsCreatedLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 2, 100, 20)];
commentsCreatedLabel.tag =54;
[commentsCreatedLabel setBackgroundColor:[UIColor clearColor]];
[commentsCreatedLabel setFont:[UIFont fontWithName:@"Helvetica"size:12]];
[cell.contentView addSubview:commentsCreatedLabel];
[commentsCreatedLabel release];

UILabel *blogDateLabel = [[UILabel alloc] initWithFrame:CGRectMake(210, 2, 65, 20)];
blogDateLabel.tag =60;
//[blogDateLabel setBackgroundColor:[UIColor grayColor]];
[blogDateLabel setBackgroundColor:[UIColor clearColor]];
[blogDateLabel setFont:[UIFont fontWithName:@"Helvetica"size:12]];
[cell.contentView addSubview:blogDateLabel];
[blogDateLabel release];

CGSize labelsize;
UILabel *commentsTextLabel = [[UILabel alloc] init];;
commentsTextLabel.tag =50;
[commentsTextLabel setNumberOfLines:0];
[commentsTextLabel setBackgroundColor:[UIColor clearColor]];
NSString *text=[[self.blogTextArray objectAtIndex:indexPath.row]capitalizedString];
[commentsTextLabel setFont:[UIFont fontWithName:@"Helvetica"size:14]];
labelsize=[text sizeWithFont:commentsTextLabel.font constrainedToSize:CGSizeMake(268, 2000.0) lineBreakMode:UILineBreakModeWordWrap];
commentsTextLabel.frame=CGRectMake(10, 24, 268, labelsize.height);
[cell.contentView addSubview:commentsTextLabel];
[commentsTextLabel release];


UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
[deleteButton setFrame:CGRectMake(280, 3, 26, 36)];
deleteButton.contentMode = UIViewContentModeScaleAspectFill;
UIImage *newImage12 = [UIImage imageNamed:@"delete1.png"];
deleteButton.tag=indexPath.row;
[deleteButton setBackgroundImage:newImage12 forState:UIControlStateNormal];
[deleteButton setBackgroundImage:newImage12 forState:UIControlStateHighlighted];
[deleteButton addTarget:self action:@selector(deletePostMethod:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:deleteButton];

}

heightForRowAtIndexPath method is important to write because unless this table view cell height will not change.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{
CGSize labelsize;
UILabel * textDesc1 = [[UILabel alloc] init];
[textDesc1 setNumberOfLines:0];
textDesc1.text=[[self.blogTextArray objectAtIndex:indexPath.row]capitalizedString];
[textDesc1 setFont:[UIFont fontWithName:@"Helvetica" size:14.0]];
labelsize=[textDesc1.text sizeWithFont:textDesc1.font constrainedToSize:CGSizeMake(268, 2000.0)lineBreakMode:UILineBreakModeWordWrap];
labelsize.height=labelsize.height+35;
[textDesc1 release];
return (CGFloat)labelsize.height;
}

Sorting Array in increasing order

Most of the time sorting is needed and for that most of the person think of various sorting algorithms.
This blog describe how to sort an array which contain numbers into ascending order with minimum coding effort.

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:nil
ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [sortValuesArray sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"sortedArray%@",sortedArray);


Happy Coding!!

Friday 26 August 2011

Uploading Video Files to Web Server

Uploading video files in iphone projects is very cumbersome.
This Blog describes how to upload video files on server using ASIFormDataRequest Method.

NSURL *urlvideo = [info objectForKey:UIImagePickerControllerMediaURL];


urlvideo contains the URL of that video file that has to be uploaded. Then convert the url into NSString type because setFile method requires NSString as a parameter

NSString *urlString=[urlvideo path];

NSLog(@"urlString=%@",urlString);
NSString *str = [NSString stringWithFormat:@"path of server"];
NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setFile:urlString forKey:@"key foruploadingFile"];
[request setRequestMethod:@"POST"];
[request setDelegate:self];
[request startSynchronous];
NSLog(@"responseStatusCode %i",[request responseStatusCode]);
NSLog(@"responseStatusCode %@",[request responseString]);

Sending Request to WebServer from iPhone App

Most of the apps have the communication with servers as the request is send from app and the response is received from server.
This blog describes how to send request on web servers and how to retrieve response of that request.


First we have to download ASIHTTPREQUEST package and copy it in our project.

You can download it from https://github.com/pokeb/asi-http-request/tree



Now you have to add the following frameworks in your frameworks folder:-

CFNetwork, SystemConfiguration, MobileCoreServices, CoreGraphics and zlib

click on framework -add- add existing framework





like this add rest of the frameworks.




In your ViewController.h file import these classes

#import "ASIHTTPRequest.h"
#import "ASINetworkQueue.h"
#import "ASIFormDataRequest.h"

//Create an instance of ASINetworkQueue
ASINetworkQueue *networkQueue;

you do not need to synthesize it.

-(void)getRegistrationResponseFailed:(ASIFormDataRequest *)req;
-(void)getRegistrationResponse:(ASIFormDataRequest *)req;
-(void)companyResponse:(ASIHTTPRequest *)req;
-(void)companyResponseFailed:(ASIHTTPRequest *)req;


In your ViewController.m file write code below:-

#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"

In your ViewDidLoad method write:-

networkQueue=[[ASINetworkQueue queue]retain];


Write the following code where you have to send request:-

There are various methods of sending request to server

The method below is POST Method

//create the url where the reqest will be send

NSString *str = [NSString stringWithFormat:@"%@/register.php",appUrl];
NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];

//setPostValue contains the value that you have to send if needed and forKey contains the key (means which script if you are calling in that the key name for the value parameter).

[request setPostValue:userMailTextField.text forKey:@"email"];
[request setPostValue:nicknameTextField.text forKey:@"nickName"];
[request setPostValue:passwordTextField.text forKey:@"password"];

[request setRequestMethod:@"POST"];
[request setDelegate:self];
//getRegistrationResponse and getRegistrationResponseFailed are the methods that will be called when either request will successfully execute or will fail.

[request setDidFinishSelector:@selector(getRegistrationResponse:)];
[request setDidFailSelector:@selector(getRegistrationResponseFailed:)];
[networkQueue addOperation: request];
[networkQueue go];



-(void)getRegistrationResponseFailed:(ASIFormDataRequest *)req
{
[indicator stopAnimating];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Could not get a response from the server.Please try again after some time" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}


-(void)getRegistrationResponse:(ASIFormDataRequest *)req
{
[indicator stopAnimating];
NSData *response=[req responseData];
NSString *string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"congrats" message:@"request send successfully" time" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];

}


GET Method of sending request:-


NSString *str = [NSString stringWithFormat:@"http://neptuneapps.com/bizproxapp/phpscripts /getBusinesses.php?categoryid=%@",mainbusinessID];
NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
[request setRequestMethod:@"GET"];
[request setDelegate:self];
[request setDidFinishSelector: @selector(companyResponse:)];
[request setDidFailSelector: @selector(companyResponseFailed:)];
[networkQueue addOperation: request];
[networkQueue go];

-(void)companyResponseFailed:(ASIHTTPRequest *)req
{
[indicator stopAnimating];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Could not get a response from the server.Please try again after some time" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}


-(void)companyResponse:(ASIHTTPRequest *)req
{
[indicator stopAnimating];
NSData *response=[req responseData];
NSString *string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"congrats" message:@"request send successfully" time" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];

}


Things to remember:-

in dealloc mehod write:-

- (void)dealloc {
[networkQueue cancelAllOperations];
[networkQueue release];

[super dealloc];
}

in viewWillDisappear write :-

-(void)viewWillDisappear:(BOOL)animated
{
[networkQueue cancelAllOperations];

}

Thursday 25 August 2011

World of ios4.3

Welcome to world of ios4.3

Feature Enhancements in ios4.3:-

• AirPlay Enhancements
AirPlay is a technology that lets your application stream audio and now Video to Apple TV and to third-party AirPlay speakers and receivers. Once the user chooses to play your audio and now Video using AirPlay, it is routed automatically by the system.

• Safari Performance
Now surf the web as fast as in iOS (4.2)2

• iTunes Home Sharing
• iPad Side Switch
• Personal Hotspot for iPhone 4
Now Enable Personal Hotspot and share your cellular data connection with your Mac, PC, iPad, or other Wi-Fi-capable device. You can share your connection with up to five devices at once over Wi-Fi, Bluetooth, and USB .Every connection is password protected and secure. And it’s power friendly, too.

• iPad Features(Multitasking):-

1. You pinch to get to the Home screen (instead of pressing the home button)
2. Swipe up to reveal the multitasking tray (instead of double-clicking the home button)
3. Swipe left and right to switch apps

Crack Nutshells of ios4.3:-
Time for the ios developers to take a sound breath because this section describes the developer-related features introduced in ios 4.3

AirPlay Video Support:-

Support for playing video using AirPlay is included in the MPMoviePlayerController class. This support allows you to play video-based content on AirPlay–enabled hardware such as Apple TV. When the allowsAirPlay property of an active MPMoviePlayerController object is set to YES and the device is in range of AirPlay–enabled hardware, the movie player presents the user with a control for sending the video to that hardware. (That property is set to NO by default.)

allowsAirPlay=YES;

For web-based content, you can enable AirPlay Video in the QuickTime Plug-in or HTML5 video element as follows:

QTPlug-in:
● airplay="allow"
● airplay="deny"(Default)

For example: <embed src="movie.mov" width="320" height="240" airplay="allow">

HTML5 video element:

● x-webkit-airplay="allow"
● x-webkit-airplay="deny"(Default)

For example: <video controls width="640" height="368" x-webkit-airplay="allow" src="content/side_with_the_seeds.mov"> </video>

Framework Enhancements:-

The following sections highlight the significant changes to frameworks and technologies in iOS 4.3

AV Foundation Framework:-
The AV Foundation framework includes the following enhancements

1.)The AV Foundation framework added the following classes for tracking network playback statistics.

• AVPlayerItem
• AVPlayerItemAccessLogEvent
• AVPlayerItemErrorLogEvent

2.)The AVMetadataItem class added support for loading key data asynchronously.

iAd Framework:-
The ADInterstitialView class is a view that you can use to embed full-screen banners into your content. You can present these banners modally or as part of a transition from one page of content to another.

UIKit Framework:-
The UIViewController class added the disablesAutomaticKeyboardDismissal method, which you can use to override the default input view dismissal behavior.

Media Player Framework:-
The Media Player framework includes the following enhancements:

1.)The MPMoviePlayerController class supports playback of video content using AirPlay.

2.)The Media Player framework added the following classes for tracking network playback statistics.

1. MPMovieAccessLog,
2. MPMovieErrorLog,
3. MPMovieAccessLogEvent
4. MPMovieErrorLogEvent

3.)The MPMoviePlayerController class now includes properties for accessing log information.


Core Audio Framework:-
The Audio Unit and Audio Toolbox frameworks include the following enhancements

1.)The AudioUnitParameterHistoryInfo struct (in the Audio Unit framework) along with supporting audio unit properties adds the ability to track and use parameter automation history.

2.) The ExtendedAudioFormatInfo struct (in the Audio Toolbox framework) lets you specify which codec to use when accessing the kAudioFormatProperty_FormatList property.

3.)The kAFInfoDictionary_SourceBitDepth dictionary key and the kAudioFilePropertySourceBitDepth property (in the Audio Toolbox framework) provide access to the bit depth of an audio stream.

4.)The kAudioConverterErr_NoHardwarePermission result code (in the Audio Toolbox framework) indicates that a request to create a new audio converter object cannot be satisfied because the application does not have permission to use the requested hardware codec.

I hope this document will help you in understanding and developing applications in ios4.3.
Happy Coding!!!!:)

Adding To Favorites Functionality

In most of the apps of iphone there is an option of favorites .You can add items to favorite list,remove items and view items marked as your favorites ones.

This wiki includes the complete implementation of favorites functionality

In your AppDelegate.h file create a favorite array.

NSMutableArray *favoritesArray;
make the property and synthesize it.

In your AppDelegate.m file

- (void)applicationDidFinishLaunching:(UIApplication *)application {

//Create an instance ofNSUserDefaults

NSUserDefaults *stdDefaults=[NSUserDefaults standardUserDefaults];
if([stdDefaults valueForKey:@"favorites"] == nil)
[self setFavoritesArray:[[NSMutableArray alloc]init]];
else
[self setFavoritesArray:[NSMutableArray arrayWithArray:[stdDefaults valueForKey:@"favorites"]]];

}

- (void)applicationWillResignActive:(UIApplication *)application{

if(updated == NO){
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:favoritesArray forKey:@"favorites"];
[NSUserDefaults resetStandardUserDefaults];
updated = YES;
}
}

- (void)applicationWillTerminate:(UIApplication *)application {
// Save data if appropriate

if(updated == NO){
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:favoritesArray forKey:@"favorites"];
[NSUserDefaults resetStandardUserDefaults];
updated = YES;
}
}


Before adding the item in the favorites we check if it already exists or not.If it does not exist it gets added else the popup appears.




-(IBAction)addToFavorites
{
once = NO;

for(int i=0;i<[[appDelegate favoritesArray] count];i++)
{
NSDictionary *tempFavDict = [[appDelegate favoritesArray] objectAtIndex:i];
NSArray *key=[tempFavDict allKeys];
NSDictionary *dkeydict=[tempFavDict objectForKey:[key objectAtIndex:0]];
NSString *businessName = [dkeydict valueForKey:@"name"];

if([name isEqualToString:businessName]){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Already added" message:nil
delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil ,nil];
[alert show];
alert.tag=1;
[alert release];
once=YES;
break;
}
}
if(once==NO)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message: @"Do you want to add this business to your Favorites ?"
delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
[alert show];
alert.tag=2;
[alert release];

}
}







Now on the button click or wherever you want to add items in your favorite list add code:-

In the following code I have created a favoriteDict dictionary which contains all the values and adding that dictionary into favorites array.


- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
if(alertView.tag==2)
{
if(buttonIndex==0)
{
return;
}
if(buttonIndex==1)
{
NSMutableDictionary *favoriteDict=[[NSMutableDictionary alloc] init];
NSDate *dat=[NSDate date];
NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSString *favDate=[formatter stringFromDate:dat];
[formatter release];
[favoriteDict setObject:favDate forKey:@"date"];
[favoriteDict setObject:self.name forKey:@"name"];
[favoriteDict setObject:self.address forKey:@"address"];
[favoriteDict setObject:self.description forKey:@"description"];
[favoriteDict setObject:self.contact forKey:@"contact"];
[favoriteDict setObject:self.phone forKey:@"phone"];
[favoriteDict setObject:self.email forKey:@"email"];
[favoriteDict setObject:self.website forKey:@"website"];

//[favoriteDict setObject:self.code forKey:@"businesscode"];
[busniessCodeFavorite setObject:favoriteDict forKey:self.code];
[appDelegate.favoritesArray addObject:busniessCodeFavorite];

//Resetting favorites in NSUserDefaults

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:appDelegate.favoritesArray forKey:@"favorites"];
[NSUserDefaults resetStandardUserDefaults];
[favoriteDict release];

//NSLog(@"appdelegate favories array%@",appDelegate.favoritesArray);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message: @"Added To Favorites"
delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
}
}




The selected item is added in favorites Array now create a link where your favorite item list will be displayed




Tuesday 23 August 2011

UIPageControl Tutorial


You have to make two view Controllers
First :- That will contain your scrolling and deegate implementation.
Second:-That will describe what you want to show in your view.

the first file should be the same and you might do changes in your second file depending on your layout requirements.

First:-
In your .h file (MyCardsViewController.h)

#import <UIKit/UIKit.h>


@interface MyCardsViewController : UIViewController <UIScrollViewDelegate>{

UIScrollView *scrollView;
IBOutlet UIPageControl *pageControl;
NSMutableArray *viewControllers;

// To be used when scrolls originate from the UIPageControl
BOOL pageControlUsed;
}

@property (nonatomic, retain) IBOutlet UIScrollView *scrollView;
@property (nonatomic, retain) IBOutlet UIPageControl *pageControl;
@property (nonatomic, retain) NSMutableArray *viewControllers;

- (IBAction)changePage:(id)sender;

@end

In your .m file (MyCardsViewController.m)

#import "MyCardsViewController.h"
#import "MyViewController.h"

static NSUInteger kNumberOfPages = 3;

@interface MyCardsViewController (PrivateMethods)

- (void)loadScrollViewWithPage:(int)page;
- (void)scrollViewDidScroll:(UIScrollView *)sender;

@end


@implementation MyCardsViewController
@synthesize scrollView, viewControllers,pageControl;


/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
*/
- (void)viewDidLoad {
self.navigationController.navigationBar.hidden=YES;
[super viewDidLoad];

// view controllers are created lazily
// in the meantime, load the array with placeholders which will be replaced on demand
NSMutableArray *controllers = [[NSMutableArray alloc] init];
for (unsigned i = 0; i < kNumberOfPages; i++) {
[controllers addObject:[NSNull null]];
}
self.viewControllers = controllers;
[controllers release];

// a page is the width of the scroll view
scrollView.pagingEnabled = YES;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * kNumberOfPages, scrollView.frame.size.height);
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.scrollsToTop = NO;
scrollView.delegate = self;

pageControl.numberOfPages = kNumberOfPages;
pageControl.currentPage = 0;

// pages are created on demand
// load the visible page
// load the page on either side to avoid flashes when the user starts scrolling
[self loadScrollViewWithPage:0];
[self loadScrollViewWithPage:1];
}

- (void)loadScrollViewWithPage:(int)page {
if (page < 0) return;
if (page >= kNumberOfPages) return;

// replace the placeholder if necessary
MyViewController *controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null]) {
controller = [[MyViewController alloc] initWithPageNumber:page];
[viewControllers replaceObjectAtIndex:page withObject:controller];
[controller release];
}

// add the controller's view to the scroll view
if (nil == controller.view.superview) {
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
controller.view.frame = frame;
[scrollView addSubview:controller.view];
}
}

- (void)scrollViewDidScroll:(UIScrollView *)sender {
// We don't want a "feedback loop" between the UIPageControl and the scroll delegate in
// which a scroll event generated from the user hitting the page control triggers updates from
// the delegate method. We use a boolean to disable the delegate logic when the page control is used.
if (pageControlUsed) {
// do nothing - the scroll was initiated from the page control, not the user dragging
return;
}

// Switch the indicator when more than 50% of the previous/next page is visible
CGFloat pageWidth = scrollView.frame.size.width;
int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pageControl.currentPage = page;

// load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];

// A possible optimization would be to unload the views+controllers which are no longer visible
}

// At the begin of scroll dragging, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
pageControlUsed = NO;
}

// At the end of scroll animation, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
pageControlUsed = NO;
}

- (IBAction)changePage:(id)sender {
int page = pageControl.currentPage;

// load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];

// update the scroll view to the appropriate page
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:YES];

// Set the boolean used when scrolls originate from the UIPageControl. See scrollViewDidScroll: above.
pageControlUsed = 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 {
self.pageControl=nil;
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}


- (void)dealloc {
[pageControl release];
[viewControllers release];
[scrollView release];
[pageControl release];
[super dealloc];
}

@end

in your this viewController xib add a scrollview and a page control and bind it.

Start up with secondViewController

in .h file:-

int pageNumber;
UIImageView *imageView;
}


@property(nonatomic,retain) IBOutlet UIImageView *imageView;

- (id)initWithPageNumber:(int)page;

in .m file

+ (UIColor *)pageControlColorWithIndex:(NSUInteger)index {
if (__pageControlColorList == nil) {
__pageControlColorList = [[NSArray alloc] initWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor magentaColor],
[UIColor blueColor], [UIColor orangeColor], [UIColor brownColor], [UIColor grayColor], nil];
}

// Mod the index by the list length to ensure access remains in bounds.
return [__pageControlColorList objectAtIndex:index % [__pageControlColorList count]];
}

// Load the view nib and initialize the pageNumber ivar.
- (id)initWithPageNumber:(int)page {
if (self = [super initWithNibName:@"MyViewController" bundle:nil]) {
pageNumber = page;
}
return self;
}

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

// Set the label and background color when the view has finished loading.
- (void)viewDidLoad {
[imageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"cardview%d",pageNumber + 1]]];
self.view.backgroundColor = [MyViewController pageControlColorWithIndex:pageNumber];
}

Adwhirl Integration in iphone apps

This Blog describe how to integrate Adwhirl in your project:-
Adwhirl supports iads in ios 3.0 also.
This blog assumes that you have your application key and you have activated your supported networks.

Getting Started :-
First download the Adwhirl sdk from http://code.google.com/p/adwhirl/downloads/list
You will get a folder which contains these folders:-


Now open your project and drag adwhirl and touchJson folder in your project.
After you drag this window will appear dont forget to check copy items options



Do the same thing for adding touchJson folder also 
Now your project will look like:-


Adwhirl contains a lot of adapters network you have to check only those that you want to use.In my case i am using admobs and iAds
Check only those that you want to use:-


After that Add following frameworks:-

UIKit.framework, Foundation.framework and CoreGraphics.framework should be included in your project by default.
● AddressBook.framework
● AudioToolbox.framework 
● AVFoundation.framework
● CoreLocation.framework 
● MapKit.framework
○ weak-linked for OS 2.X support 
● MediaPlayer.framework
● MessageUI.framework 
○ weak-linked for OS 2.X support
● QuartzCore.framework 
● SystemConfiguration.framework 
● iAd.framework
○ required for iAd, weak-linked for OS 3.X support
● libsqlite3.dylib 
● libz.dylib




Now you need to download the sdk for adapter network you are using.That you can download from that ads corresponding site.
I have used Admobs so for that I have downloaded abmobs sdk
Now add that downloaded folder in the same way as added adwhirl folder.



Now You are ready with your whole integration process and you have to add few lines of code now

In your viewController.h file write:-

#import "AdWhirlDelegateProtocol.h"

add AdwhirlDelegate like this @interface AdwhirlSampleViewController : UIViewController <AdWhirlDelegate>

In your viewController.m file write:-

#import "AdWhirlView.h"

these two delegate methods of adwhirl

-(NSString *)adWhirlApplicationKey
{
return @"a98aa6af9bc04aa59d551a862320d062";
}
- (UIViewController *)viewControllerForPresentingModalView
{
return [((AdwhirlSampleAppDelegate *)[[UIApplication sharedApplication] delegate]) viewController];
}

- (void)viewDidLoad {
[super viewDidLoad];
AdWhirlView *awView = [AdWhirlView requestAdWhirlViewWithDelegate:self]; 
[self.view addSubview:awView];

}

Making rounded corners of XCode Controls

This blog describe a very basic and essential feature that is used in iPhone/iPad Applications.When we normally use label,button etc the shapes are in square form.Of course you can convert it in a rectangle by varying the width and height but the problem occurs when you have to give a rounded shape.

This is what the blog will guide you :-

First you have to add QuartzCore Framework in your project.

Add #import <QuartzCore/QuartzCore.h> in your file.

Now add these lines of code where ever you want to show your control

CALayer *l = [btn layer];
[l setMasksToBounds:YES];
[l setCornerRadius:20.0];

btn is my UIButton .You can change the value of setCornerRadius to give your desired rounded shape.

Zooming the location on the mapView within the cretain radius


This blog describe how to zoom your current location or any another location on map in certain radius.

Write the following code when you have requirement to zoom your location within a certain radius.

CLLocation *zoomLocation= map.userLocation.location;
float latitude = zoomLocation.coordinate.latitude;
float longitude = zoomLocation.coordinate.longitude;
double miles = 3.0;
double scalingFactor = ABS( (cos(2 * M_PI * latitude / 360.0) ));
MKCoordinateSpan span;
span.latitudeDelta = miles/69.0;
span.longitudeDelta = miles/(scalingFactor * 69.0);
MKCoordinateRegion region;
region.span = span;
region.center = zoomLocation.coordinate;
[map setRegion:region animated:YES];
[map regionThatFits:region];

This code will make your current location zoom within 3 miles radius on your map.

Thursday 18 August 2011

Sending Email Through iPhone Within the app



Hi All,

This Blog describes how to send the e-mail from the app.

Very First you have to attach "MessageUI" framework kit in your framework folder.

In your ViewController.h file import this class:-

#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>



In your ViewController.m file write the below code:-


if([MFMailComposeViewController canSendMail]){

MFMailComposeViewController *mail=[[MFMailComposeViewController alloc]init];
mail.mailComposeDelegate=self;
[mail setSubject:@"subject of the mail"];
[mail setMessageBody:@"Hello my first mail from iphone app" isHTML:NO];
[self presentModalViewController:mail animated:YES];
[mail release];
}

- (void)mailComposeController:(MFMailComposeViewController*)mailController didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
[self dismissModalViewControllerAnimated:YES];

}