Friday, June 24, 2011

What is difference between NSArray and NSMutableArray?

    NSMutableArray (and all other classes with Mutable in the name) can be modified.
  
    So, if you create a plain NSArray, you cannot change its contents later (without recreating it).
      
    But if you create an NSMutableArray, you can change it
      
    E.g.  NSMutableArray has methods like -addObject: and -insertObject:atIndex:
          
    NSMutableArray is editable, where as NSArray is read-only

Friday, June 17, 2011

iPhone Email - MFMailcomposeviewcontroller

In this Article we will add Email Composer in our iPhone Application

Step 1:

You have to add framework for MPMailComposer

#import <MessageUI/MessageUI.h>

#import <MessageUI/MFMailComposeViewController.h>

Step 2:

Add below mention code in you iPhone application

-(void)sendButtonClicked

{

Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));

if (mailClass != nil){

// To check whether the current device is configured for sending emails or not

if ([mailClass canSendMail]){    [self displayComposerSheet];  }

else{   [self launchMailAppOnDevice];  }

}

else{  [self launchMailAppOnDevice];}

} // End sendButtonClicked

-(void)displayComposerSheet

{

MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];

picker.mailComposeDelegate = self;

[picker setSubject:@"Enter Subject line here!"];

// Set up recipients

NSArray *toRecipients = [NSArray arrayWithObject:@"first@example.com"];

NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil];

NSArray *bccRecipients = [NSArray arrayWithObject:@"fourth@example.com"];

[picker setToRecipients:toRecipients];

[picker setCcRecipients:ccRecipients];

[picker setBccRecipients:bccRecipients];

// To Attach an image to the email

NSString *path = [[NSBundle mainBundle] pathForResource:@"attachment" ofType:@"png"];

NSData *myData = [NSData dataWithContentsOfFile:path];

[picker addAttachmentData:myData mimeType:@"image/png" fileName:@"attachment"];

// Add text to email body

NSString *emailBody = @"This is email body, change text as per your requirements!";

[picker setMessageBody:emailBody isHTML:NO];

[self presentModalViewController:picker animated:YES];

[picker release];

} // End displayComposerSheet

// To Dismisses the email composition interface when users tap on Cancel or Send. Proceeds to update the message field with the result of the operation.

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error

{

message.hidden = NO;

// show alert to users about errors associated with the interface

switch (result)

{

case MFMailComposeResultCancelled:

message.text = @"Result: canceled";

break;

case MFMailComposeResultSaved:

message.text = @"Result: saved";

break;

case MFMailComposeResultSent:

message.text = @"Result: sent";

break;

case MFMailComposeResultFailed:

message.text = @"Result: failed";

break;

default:

message.text = @"Result: not sent";

break;

}

[self dismissModalViewControllerAnimated:YES];

}

// Launches the Mail application on the device.

-(void)launchMailAppOnDevice {

NSString *recipients = @"mailto:first@example.com?                   cc=second@example.com,third@example.com&subject=Enter Subject line here!";

NSString *body = @"&body=This is email body, change text as per your requirements.!";

NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];

email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];

}

Thursday, June 16, 2011

Creating a UIView, UILabel, UIButton, UITextField programmaticaly

Let us start creating UIView programmaticaly.

Step 1 Add a UIViewController class, name it YourView.m (and YourView.h).
In YourView.h
UIView *view;

Step 2
In YourView.m un comment loadView.

// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
view.backgroundColor = [UIColor yellowColor];
self.view = view;
}

----------------------------------------------------------------------------------------------------------------

Adding a UILabel programmatically

You can use this class to draw one or multiple lines of static text, such as those you might use to identify other parts of your user interface. The base UILabel class provides control over the appearance of your text, including whether it uses a shadow or draws with a highlight. If needed, you can customize the appearance of your text further by subclassing.

UILabel *lblName = [[UILabel alloc] initWithFrame:CGRectMake(50, 200, 200, 80)];
lblName.text = @"Admin";
lblName.textAlignment = UITextAlignmentCenter;
lblName.textColor = [UIColor BlackColor];
lblName.shadowColor = [UIColor whiteColor];
lblName.shadowOffset = CGSizeMake(1,1);
lblName.font = [UIFont fontWithName:@"Zapfino" size:20];
lblName.backgroundColor = [UIColor LightGrey];
[self.view addSubview:lblName];
[lblName release];

----------------------------------------------------------------------------------------------------------------

Text wrapping/ MultiLine

UILabel can display multiple lines of text, and to make it you need to set two properties lineBreakMode and numberOfLines:
lblName.lineBreakMode = UILineBreakModeWordWrap;
lblName.numberOfLines = 2; // 2 lines ; 0 - dynamical number of lines
lblName.text = @"Kamleshwar";

This is all about UILabel. For More your can Refer Developer.Apple.com
----------------------------------------------------------------------------------------------------------------


Adding a UIButton Programmatically

A button intercepts touch events and sends an action message to a target object when tapped. Methods for setting the target and action.

btnSubmit = [[UIButton buttonWithType:UIButtonTypeRoundedRect] initWithFrame:CGRectMake(50, 200, 200, 80) ];
[btnSubmit setTitle:@"Submit" forState:UIControlStateNormal];
[btnSubmit setTitle:@"Done" forState:UIControlEventTouchDown];
[btnSubmit setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
btnSubmit.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
btnSubmit.backgroundColor = [UIColor clearColor];
[btnSubmit addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview: btnSubmit];


-(void)buttonAction:(id)sender {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert!" message:@"Button Clicked" delegate:self cancelButtonTitle:@"Cancel"         otherButtonTitles:nil];
[alert show];
[alert release];
}


If you would like to remove info about what object called the method [(id)sender], remove  colon on the end of class name in adding a selector to the button:
[btnSubmit addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];

And of Remove: ":(id)sender" from method name
-(void)buttonAction {
}

----------------------------------------------------------------------------------------------------------------
Adding a UITextField Programmatically

UITextField * txtName = [[UITextField alloc] initWithFrame:CGRectMake(10, 200, 300, 50)];
txtName.borderStyle = UITextBorderStyleRoundedRect;
txtName.textColor = [UIColor blackColor]; //text color
txtName.font = [UIFont systemFontOfSize:17.0];  //font size
txtName.placeholder = @"Please enter name";  //place holder
txtName.backgroundColor = [UIColor whiteColor]; //background color
txtName.autocorrectionType = UITextAutocorrectionTypeNo;    // no auto correction support


txtName.keyboardType = UIKeyboardTypeDefault;  // type of the keyboard
txtName.returnKeyType = UIReturnKeyDone;  // type of the return key


txtName.clearButtonMode = UITextFieldViewModeWhileEditing;    // has a clear 'x' button to the right

txtName.delegate = self;    // let us be the delegate so we know when the keyboard's "Done" button is pressed

To Remove Keyboard On Press Done Button

You typically use this UITextField to gather small amounts of text from the user and perform some immediate action, such as a search operation, based on that text.

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[txtName resignFirstResponder];
return YES;
}

Wednesday, June 15, 2011

How to split string into substring – xCode iPhone?

You can also split a string by a substring, using NString's componentsSeparatedByString method.
NSString *list = @"iPhone, Application, Development";
NSArray *listItems = [list componentsSeparatedByString:@", "];

Tuesday, June 14, 2011

Xcode – String contains string in objective-c

How to search sub string 

NSString *string = @"iPhone Application Development";
if ([string rangeOfString:@"iPhone"].location == NSNotFound
{
  NSLog(@"String does not contain iPhone");
} 
else 
{
  NSLog(@"String contains iPhone!");
}

Monday, June 13, 2011

Covert NSData to NSString, Covert NSString To NSData, UIImage to NSData

// Convert From NSString to NSData
NSString *text = @"iPhone Application Development";
NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];

// Convert From NSData to NSString
NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

// Convert From UIImage to NSData
UIImage *image = [UIImage imageNamed:@"iPhone.png"];
NSData *dataObj = UIImageJPEGRepresentation(image, 1.0);

Sunday, June 12, 2011

Regular expression for Email validation in xCode iPhone application.

To Add Email Address validation in your iPhone Application

-(BOOL)validateEmail:(NSString*)email{
if( (0 != [email rangeOfString:@"@"].length) &&  (0 != [email rangeOfString:@"."].length) )
{
NSMutableCharacterSet *invalidCharSet = [[[[NSCharacterSet alphanumericCharacterSet] invertedSet]mutableCopy]autorelease];
[invalidCharSet removeCharactersInString:@"_-"];
NSRange range1 = [email rangeOfString:@"@" options:NSCaseInsensitiveSearch];
// If username part contains any character other than "."  "_" "-"
NSString *usernamePart = [email substringToIndex:range1.location];
NSArray *stringsArray1 = [usernamePart componentsSeparatedByString:@"."];
for (NSString *string in stringsArray1) {
NSRange rangeOfInavlidChars=[string rangeOfCharacterFromSet: invalidCharSet];
if(rangeOfInavlidChars.length !=0 || [string isEqualToString:@""])
return NO;
}
NSString *domainPart = [email substringFromIndex:range1.location+1];
NSArray *stringsArray2 = [domainPart componentsSeparatedByString:@"."];
for (NSString *string in stringsArray2) {
NSRange rangeOfInavlidChars=[string rangeOfCharacterFromSet:invalidCharSet];
if(rangeOfInavlidChars.length !=0 || [string isEqualToString:@""])
return NO;
}
return YES;
}
else
return NO;
}

Saturday, June 11, 2011

Find out the iPhone/iPod Touch device ID(UDID) with/without Xcode?

How to find out the iPhone/iPod Touch device ID without Xcode?
  1. Connect the iPhone or iPod Touch to your Mac or PC (Windows Machine)
  2. Click on the device in iTunes, go to the “Summary” tab, click on the “Serial Number” label. The “Serial Number” will change to “Identifier”
  3. Click on “Edit” in the menu at the top and select “Copy”
  4. Now you can paste the device ID into an e-mail
How to find out the iPhone/iPod Touch device ID with Xcode?

UIDevice *myDevice = [UIDevice currentDevice];

NSString *deviceUDID = [myDevice uniqueIdentifier];

Friday, June 10, 2011

How to display the UITableView programmatically?

Add UITableView programmatically

Step 1.
In you file MyViewController.h

Add Protocols/ Delegates

@interface MyViewController : UITableViewController <UITableViewDelegate, UIAlertViewDelegate> {

UITableView *tableView;

}

Step 2:

Add following code in MyViewController.m file

-(void) viewDidLoad {



tableView = [[[UITableView alloc] initWithFrame:CGRectMake(0,0,320,480) style:UITableViewStylePlain] autorelease];
tableView.dataSource = self;
tableView.delegate = self;


[self.view addSubview:tableView];

}

// Default is 1 you can change as per your requirements.

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

return 1;

}

// If there is more than one section then add check for section =0,1,2,3 and return accordingly

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

return [your array count];

}

// Add cell value from your array or static(As per requirements)

- (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];

}

// Configure the cell...

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

return cell;

}

Above are 3 mandatory methods there are lots of other methods we can use as per our requirements.


Thursday, June 9, 2011


UIWebView  *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 290)]; 

//init and create the UIWebView
   
webView.autoresizesSubviews = YES;
  webView.autoresizingMask=(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);
   
[webView setDelegate:self];
   
NSString *urlAddress = @"http://www.kamleshwar.com"
   
// Web view is working with url to webpage
   
NSURL *url = [NSURL URLWithString:urlAddress];
   
   
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
   
[webView loadRequest:requestObj];
 

[[self view] addSubview: webView];  



// Upload HTML contents to Web view


NSString *html = @"iPhone Application Development Is Easy with Kamleshwar";
[webView loadHTMLString:html baseURL:nil];

Wednesday, June 8, 2011

iOS/ xCode /Objective-C Trim whitespace from string



//Remove spaces from both ends of a string

NSString *resultString = [yourString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];


//To Remove spaces and newlines from the string, use the whitespaceAndNewlineCharacterSet

NSString *resultString = [yourString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];