Wednesday, November 16, 2011

Create rounded corner UIWebView


// This is required for CALayer properties

#import "QuartzCore/QuartzCore.h"


    // Create UIWebview Object
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(5, 20, 310, 220)];

    // Create Rounded corners using CALayer property
    [[webView layer] setCornerRadius:10];
    [webView setClipsToBounds:YES];

    // Set colored border using CALayer property I have set it to white
    [[webView layer] setBorderColor:
     [[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1] CGColor]];

    [[webView layer] setBorderWidth:2.75];

    [[self view] addSubview:webView];

Friday, September 30, 2011

Convert NSString to NSDate


    NSString *dateString = @"03-Sep-11";

    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init]   autorelease];
    dateFormatter.dateFormat = @"dd-MMM-yy";

    NSDate *date = [dateFormatter dateFromString:dateString];

Thursday, September 29, 2011

Add Background Image (UIImage) To UIView


//To add a image as background for an UIView (Make sure the image is in your app’s resource bundle)
         
      - (void)viewDidLoad
      {
          self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"bgImage.png"]];
      }

xCode iOS: Set Status Bar Color and Background


User can put this code or in AppDelegate file as this will be called once in Application /Or as per requirements.

UIApplication Class
Set one of the following as per your choice:

[[UIApplication sharedApplication]
      setStatusBarStyle:UIStatusBarStyleBlackTranslucent animated:NO];
[[UIApplication sharedApplication]
      setStatusBarStyle:UIStatusBarStyleBlackOpaque animated:NO];
[[UIApplication sharedApplication]
      setStatusBarStyle:UIStatusBarStyleDefault animated:NO];

Tuesday, September 6, 2011

Difference Between @synthesize and @dynamic

//@synthesize will generate getter and setter methods for your property. @dynamic just tells the compiler that the getter and setter methods are implemented not by the class itself but somewhere else (like the superclass)

//@dynamic e.g. with subclasses of NSManagedObject (CoreData) or when you want to create an outlet for a property defined by a superclass that was not defined as an outlet:



//Super class:

@property (nonatomic, retain) NSButton *someButton;

@synthesize someButton;



//Subclass:

@property (nonatomic, retain) IBOutlet NSButton *someButton;

@dynamic someButton;

Friday, September 2, 2011

Apple Launched Mac OS X Lion

Apple has released Mac OS X Lion on its Mac App Store and, as promised, the new operating system is selling for $31.99. But if you have purchased macbook after july 2011 you can update from Apple free. for more details you can check Apple's web site, if this offer is sill open.

Mac OS X Lion (version 10.7) is the eighth major release of Mac OS X, Apple's desktop and server operating system for Macintosh computers. Lion was released on July 20, 2011, as announced during Apple's third quarter 2011 earnings report. Apple's homepage and Mac OS X webpages refer to it as OS X Lion, without the "Mac", although Apple's press release for Lion's July release mainly uses "Mac OS X Lion" rather than "OS X Lion". Built on a rock-solid UNIX foundation, OS X is engineered to take full advantage of the technologies in every new Mac. And to deliver the most intuitive and integrated computer experience.

There's no going into an Apple store and buying a copy of this new OS for Intel-based Apple laptops and desktops on a DVD. Apple provides thumb drive as well for OS X Lion. Mac OS X Lion - which touts more than 250 new features - is only available as a 3.49-gigabyte digital download. Apple store employees will, however, help with downloading Lion for those who stroll in.

Since the company that makes the Mac creates the software on every Mac, you get a fully integrated system in which everything works together perfectly. OS X works with the processor in your Mac to deliver the best possible performance. The Multi-Touch track pad on every Mac notebook gives you more than enough space to pinch, swipe, and tap your way around most of the apps on your system. OS X gives you long battery life by dimming the screen in low-light conditions and even regulating processor activity between keystrokes.

Among the new features Lion is adding over its predecessor, OS X Snow Leopard, are new multi-touch track-pad features, including scrolling speed that varies depending on how fast you flick your fingers, pinching your fingers to zoom in on a web page or image and new security features such as stepped-up hard drive encryption.

Apple will ship OS X Lion exclusively via the Mac App Store next month. The company has posted an extensive list of 250 new features and improvements within the OS. We've found some more information, including clarification that previous concerns are answered by news it will be possible to download OS X Lion from the Mac App Store just once in order to upgrade large numbers of Macs.

Quick Overview of Mac features:

There are approx. 250 new features in Mac OS X Lion few of those are
Multi-Touch Gestures
Full-screen apps
Mission Control
Language Support
Launchpad etc.
MAC OS X LION will automatically saves your changes as you go, so you never have to worry about losing work. Also will keeps history of your document as you work & presents.

Wednesday, August 31, 2011

Apple after Steve Jobs

Steve Jobs resignation has created a deep impact on the tech world. All tech giants are shocked about the news as he is the most successful person who brought Apple to the peak. But, will Apple improve in his absence? This is the greatest question in the world of technology. It is quite discouraging for Apple when Steve jobs left but the successors are no less. Who are those supporting hands?

Tim cook
Bob Mansfield
Peter Oppenheimer
Jony Ive
Phil Schiller
Scott Forstall


Tim cook
He was the Chief Operating Officer of Apple Inc since 2005. He is now appointed as the CEO of the most innovative company in the world. He is a relentless leader who works with a lot of dedication. Once when Steve took a health vacation, it was Tim who had to run the day to day operations. Tim is from a small town, a football fanatic. He does have a remarkable vision and Steve has full faith on him shows he is really a very dignified person. Cook joined Apple in 1998, hired by Jobs to tackle Apple's operations.


Bob Mansfield
The Senior Vice President of Macintosh hardware engineering who is in direct touch with the CEO. He joined Apple in the year 1999 and with his team has created a breakthrough of their products like MacBook Air and the all-in-one iMac line. Previously he was a Vice President at Raycer Graphics that apple purchased in 1999. Mansfield earned a BSEE degree from The University of Texas at Austin in 1982.


Jony Ive
An English designer and the Senior Vice President of industrial design at Apple Inc have created a very strong and concrete foundation for himself in the company. H
e designed the products like iMac, titanium and aluminum pwerbook G4, G4 cube, Macbook, Unibody MacBook pro, MacBook air, iPod, iPhone and iPad. He has already created the best designs and for sure will continue and improve on it.

Phil Schiller
Being a product marketing boss of the company he is doing a lot of stuffs. He is the one who hammers out the contract with Google and protects the appications store which is a technically not that easy. He is also a key executive at Apple. He is the well known executive at apple. When Steve was out on the vacation he announced about the iPhone 3GS. He was with Jobs and Forstall to speak at WWDC and will also show his presence on the introduction of iPhone 5 in October.


Peter Oppenheimer
He is the Chief Financial Officer of Apple Inc who has done a fine job for all these years. There are speculations about him getting involved in project deals
of iPad. He takes care of treasury, investor relations, tax, information systems, internal audit and facilities functions. He serves the company's executive committee. Oppenheimer obtained his bachelor's degree from California Polytechnic University, San Luis Obispo and an M.B.A. from the University of Santa Clara, both with honors.


Scott Forstall
He is the Senior Vice President of the iOS software, the heart of Apple's product. The rival Google wants to compete with apple for which they brought Motorola and Microsoft planning to have a tie up with Nokia as well. So Apple has got a tough competition and now they are more of in need of Forstall. He joined Apple in the year 1997. He has done his Bachelor of Science in Symbolic Systems and a Master of Science in Computer Science from Stanford University. He was the only person who accompanied Jobs and represented as a executive and spoke on the stage at the company's worldwide developer conference this year.


Friday, August 26, 2011

Released - iOS 5 for iPhone, iPad, iPod touch [Beta - Developers Only]

Apple at Worldwide Developers Conference has announced the next major release of iOS for iPhone, iPad and iPod touch. This release, which brings tons of new features is available as of today to developers for testing purposes.

Which devices are supported you may ask? Well, this time, iPhone 4, iPad 2, iPad (1st-gen), iPhone 3GS and the 4th & 3rd-gen iPod touches are all going to be supported. This debunks the rumor which we heard earlier about iPhone 3GS not getting iOS 5.

The new iOS 5 includes over 200 new features, not to forget over 1500 new APIs for developers to take advantage of. There are 10 new key features, including new revamped notifications system called ‘Notification Center’, which according to Apple is going to be the industry’s best implementation. Other features include: Newsstand, Twitter integration, Safari Reader, Reading List, tabbed browsing for iPad, Reminders, Camera updates, Mail updates, built-in dictionary, PC-free (no cables required), OTA software updates, updates to Game Center, iMessage, AirPlay mirroring for iPad.

Just like with any other beta release, this version of iOS is only available to developers who are enrolled in the iPhone Developer Standard or Enterprise Program. If you are a registered developer in either of these two programs, then you can access all the beta bits today by signing into Apple Developer Connection (which is also knows as iOS Dev Center) here.
iOS 5 is slated for public release later this fall, probably in line with the next-gen iPhone 5/4S release.

DevCenter so that developers can go and download the iOS 5 Beta!

Downloads include:
iOS 5 beta (iPad 2 Wi-Fi)
iOS 5 beta (iPad 2 GSM)
iOS 5 beta (iPad 2 CDMA)
iOS 5 beta (iPad)
iOS 5 beta (iPhone 4 GSM)
iOS 5 beta (iPhone 4 CDMA)
iOS 5 beta (iPhone 3GS)
iOS 5 beta (iPod touch 4th generation)
iOS 5 beta (iPod touch 3rd generation)
Xcode 4.2 and iOS SDK 5 beta (Snow Leopard)
Xcode 4.2 and iOS SDK 5 beta (Lion)

Thursday, August 25, 2011

Steve Jobs (CEO, Apple) resigned

Steve Jobs resigned as CEO of Apple Inc on Wednesday and passed the reins to his right-hand man Tim Cook, saying he could no longer fulfill the duties in a stunning announcement that raised fears his health has deteriorated further.

I have always said if there ever came a day when I could no longer meet my duties and expectations as Apple’s CEO, I would be the first to let you know. Unfortunately, that day has come.

As far as my successor goes, I strongly recommend that we execute our succession plan and name Tim Cook as CEO of Apple.

I believe Apple’s brightest and most innovative days are ahead of it. And I look forward to watching and contributing to its success in a new role.

“Steve’s extraordinary vision and leadership saved Apple and guided it to its position as the world’s most innovative and valuable technology company,” said Art Levinson, Chairman of Genentech, on behalf of Apple’s Board. “Steve has made countless contributions to Apple’s success, and he has attracted and inspired Apple’s immensely creative employees and world class executive team. In his new role as Chairman of the Board, Steve will continue to serve Apple with his unique insights, creativity and inspiration.”

But the company’s shares still dived as much as 7 per cent in after-hours trade after the industry icon, who has been on medical leave for an undisclosed condition since January 17, announced he will be replaced by COO and heir apparent Cook.

“Investors are very comfortable with Tim Cook even though Jobs has been a driver of innovation and clearly an Apple success. Tim has shown Apple can still outperform extremely well when he’s been acting as CEO,” said Cross Research analyst Shannon Cross.

“I don’t know if it’s a health issue. I don’t know if it is a shock. Most likely it was going to happen at some point. Why today versus another day? I don’t know.”

Monday, August 1, 2011

How to add an existing framework in Xcode 4?

How to add an existing framework in Xcode 4

There are lots of changes in new Xcode 4 version and it makes developer bit confused. Find the way to Add an existing Framework.

Follow below mention steps :

1. Click your project in Navigator area

2. Select 'TARGETS' in the next column

3. Click the 'Build Phases'

4. Select 'Link Binary With Libraries'

Here you can see '+' button at the bottom in the area. On click it will show list of frameworks that you can add to your project. 


Saturday, July 23, 2011

Add UITextField Programmatically


//Add UITextField Programmatically 
CGRect textFieldFrame = CGRectMake(0.0, 0.0, 100.0, 30.0);
UITextField *txtField = [[UITextField alloc] initWithFrame:textFieldFrame];
// default is UITextBorderStyleNone. If set to UITextBorderStyleRoundedRect, custom background images are ignored.

[txtField setBorderStyle:UITextBorderStyleRoundedRect];
[txtField setTextColor:[UIColor blackColor]];
[txtField setFont:[UIFont systemFontOfSize:20]];
[txtField setDelegate:self];
[txtField setPlaceholder:@"Add Your Placeholder Text Here"];
[txtField setBackgroundColor:[UIColor whiteColor]];
txtField.keyboardType = UIKeyboardTypeDefault;

Create a UISwitch Programmatically


//Add Below code in ViewDidLoad or LoadView


CGRect frame = CGRectMake(0.0, 0.0, 60.0, 26.0);
UISwitch *switchControl = [[UISwitch alloc] initWithFrame:frame];
[switchControl addTarget:self action:@selector(actionSwitch:) forControlEvents:UIControlEventTouchUpInside];

[switchControl setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:switchControl];

Friday, July 22, 2011

Create the UIScrollView Programmatically

With the help of  the UIScrollView we will able to  display content that is larger than the size of the application’s window. It enables users to scroll the view and to see the full contents.

//Creating the scroll view
UIScrollView *scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; 

//Create the views which are going to display in the scrollview.
int count= 4;
for (int i = 0; i
{
    CGFloat y = i * self.view.frame.size.width;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, 0self.view.frame.size.widthself.view.frame.size.height)];
    view.backgroundColor = [UIColor greenColor];
    [scrollview addSubview:view];
    [view release];
}

// X will place every UIView exactly where the previous UIView 's frame ended.

// The x and y coordinates for creating the new 4 views will be.
-(0,0)(320,0)(640,0)(960,0)  

// We are increasing the x coordinate to 320, We can able to add the views horizontally one after other.
// ContentSize is nothing, it is size of the total view(Total size of 4 views) Content size will be (1280,480)
// Set the UIScrollView contentSize 
scrollview.contentSize = CGSizeMake(self.view.frame.size.width * count, self.view.frame.size.height); 

Move Image using UITouch methods in XCode iOS


Declare UIImageView in .h file

UIImageView *imageView;

And rest code will be in .m file

// On Load View Assign image to UIImageView
- (void)viewDidLoad
{
// Get image from resource folder with image name
UIImage *image = [UIImage imageNamed:@"Sample.png"];
// Set Frame size as per image height & width
CGRect frame = CGRectMake(00, image.size.width, image.size.height);
// Allocate memory and set frame for image view
imageView = [[UIImageView allocinitWithFrame: frame];
// Add Image view to main view
[self.view addSubview: imageView];
}

// On touch Image will move to touch location
-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch *touch = [[event allTouchesanyObject];
// Get Touch location
CGPoint touchLocation = [touch locationInView:touch.view];
// Set touch location's center to ImageView
imageView.center = touchLocation;
}

// To Move image with touch You can 
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{
// get touch event
UITouch *touch = [[event allTouchesanyObject];
CGPoint touchLocation = [touch locationInView:self.view];
if ([touch view] == imageView) 
{
// move the image view
imageView.center = touchLocation;
}
}

Wednesday, July 20, 2011

Xcode iOS, Objective C: What is Protocol?

A protocol is means to define a list of required and/or optional methods that a class implements. If a class adopts a protocol, it must implement all required methods in the protocols it adopts.

Cocoa uses protocols to support interprocess communication through Objective-C messages. As Objective-C does not support multiple inheritance, you can achieve similar functionality with protocols, as a class can adopt more than one protocol.

An Example of a protocol is NSCoding, which has two required methods that a class must implement.
This protocol is used to enable classes to be encoded and decoded, that is, archiving of objects by writing to permanent storage.

Another example is when using a tableview, your class implements thecellForRowAtIndexPath method which asks for cell content to insert into a table – thecellForRowAtIndexPath method is defined within the UITableViewDataSource protocol.

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

Wednesday, May 18, 2011

Beat the Heat

Here are some of the smart ways to beat the heat this summer, no matter which country you reside in.

  • Besides drinking plenty of water, drink a lot of fluids to avoid dehydration. The ever-popular “nimbu pani” or lemonade is an excellent drink to feel refreshed. If you are cautious of drinking lemonade, then the natural thirst-quencher is tender coconut water. Tender coconut water contains sugar, fiber, and proteins along with vitamins and minerals. But not direct cold water. Mix cold water with normal water.
  • Never have water just after returning from the hot scorching rays of the sun
  • Exercise early morning.
  • Try not to shampoo too often as they make your hair stick to your face .This will make you feel too stuffy.
  • Eat a lot of salads and fresh fruits that naturally contain water, like water melon – in fact this fruit contains nearly 92% water and up to 14% of vitamin C. This will add to the moisture content that you will lose through sweating. Small amounts of vitamin B and potassium are also found in this fruit.
  • Drink water that is stored in earthenware pots. This method is popular in rural India so that they can beat the heat with cool drinking water.
  • Avoid eating oily food and especially avoid eating cut fruit from vendors as it may have been exposed to flies and dust.
  • For long lasting make-up, avoid moisturizer, especially if you have oily skin, and dust on some loose powder to seal the oil in.
  • Try to get some parking only in shady areas! This will ensure that your car does not heat up while you are out!
  • Keep a hand held fan to use so that you can keep cool when you are outdoors.
  • A parasol is very helpful to remain cool when you go outdoors. A pair of sunglasses will also help tremendously to keep the glare out. You can wear golf caps to avoid getting sun burnt.
  • When you feel warm indoors hang a wet sheet by a window, which is open. This way you will get cool air from the water as it evaporates and blows toward you from the open window.
  • Close your windows before it gets too hot outside.
  • You could keep a spray bottle filled with water in the refrigerator so that you can spray yourself at regular intervals. The evaporation of the water will cool down the blood flowing through your veins.
  • People who live in India enjoy a spicy meal even when it’s hot, since the capsaicin in the hot peppers will make them perspire and when the sweat evaporates it makes one feel quite cool! So do try a spicy dish on a hot summer day in India to experience this magic! Avoid oil and spice as much as you can
  • If all else fails, why don’t you take a break and head to any of India’s hill stations and refresh yourself with its breathtaking beauty?
  • Always wear light loose and cotton clothes
  • Stick to light colors, especially white
  • Try taking a nice nap in the afternoon for better health insurance. This freshens your body effectively. (But not in Office J )
  • Always have light meals in between lunch and dinner.
  • Have tea, this makes your teeth and eyes from going dull in summer.