My Connections

Business card

Tuesday, December 28, 2010

Circular Picker View

Hi to all iPhone Players, Some time while working on Picker View Controller may be you faced a issues of  limited picker view display, means your picker view wheel is not moving continuously, its stoping on the last Value. but you want it to move circularly with the same values.

here is a Solution to get the same effect :

just manipulate your picker view delegate methods like this...



- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSUInteger)row forComponent:(NSUInteger)component; {
NSMutableArray *strings = [NSMutableArray arrayWithCapacity:10];
[strings addObject:@"Zero"];
[strings addObject:@"One"];
[strings addObject:@"Two"];
[strings addObject:@"Three"];
[strings addObject:@"Four"];
[strings addObject:@"Five"];
[strings addObject:@"Six"];
[strings addObject:@"Seven"];
[strings addObject:@"Eight"];
[strings addObject:@"Nine"];
return [strings objectAtIndex:(row%10)];
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSUInteger)row inComponent:(NSUInteger)component {
[self pickerViewLoaded:nil];
}

- (NSUInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSUInteger)component {
return 16384;
}


-(void)pickerViewLoaded: (id)blah {
NSUInteger max = 16384;
NSUInteger base10 = (max/2)-(max/2)%10;
[myPickerView selectRow:[myPickerView selectedRowInComponent:0]%10+base10 inComponent:0 animated:false];
}


- (NSUInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}


to get the Source Code, click here.

Friday, October 22, 2010

How to draw a graph (pie chart) using iPhone SDK

There are two ways:
1. by using google API for charts

    In this you just have to pass value through URL and google will return you a Graph Image, Then you can use it easily.


2. Another way is to use Graphics Methods

    I have an example for the same....

get it frm HERE.

Wednesday, October 6, 2010

iPhone FBConnect: Facebook Connect Tutorial


UPDATE: Please have a look to the updated post here...

http://viksiphoneblog.blogspot.in/2013/01/integration-of-facebooksdk-into-ios-50.html






By following these steps you can easily integrate with Facebook using FBConnect...

Create a Viewbased Application with name ‘FacebookAPI’.

before that:

1.Download Facebook Connect for iPhone SDK (http://svn.facebook.com/svnroot/platform/clients/packages/fbconnect-iphone.zip) or you can download same from here

Just go through the project. In particular, the “Connect” sample project. Sample Project gives demo of some of the functionality.

1.1.Open src/FBConnect.xcodeproj from SDK that you downloaded, and your own project as well.

1.2.Drag n drop FBConnect group. Make sure “Copy items into destination group folder” is NOT checked. It should look as shown below

1.3.Go to Project Menu ->Edit project settings and scroll down to “User Header Search Path” add entry which will point to “src folder”

1.4.To test import all .m n .h files in case any miss. And compile.

2.Login to Facebook. After that go to Developers Page (http://www.facebook.com/developers/) as shown below.

3.Register your application with Facebook

3.1.Click on Set up New Application Button in the upper right hand corner.

3.2.Give Application name and click on create application button. Then you will see new application screen with detail including “API key”and “API Secret Key”

Note : This application will not work until you provide your Facebook application’s API keys.

Now to get started with actual coding:

Append Following code in FacebookAPIAppDelegate.h

  #import
#import "FBConnect/FBConnect.h"
#import "FBConnect/FBSession.h"

@class FacebookAPIViewController;

@interface FacebookAPIAppDelegate : NSObject {
UIWindow *window;
FacebookAPIViewController *viewController;
FBSession *_session;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet
FacebookAPIViewController *viewController;
@property (nonatomic,retain) FBSession *_session;
@end


Append Following code in FacebookAPIAppDelegate.m


 #import "FacebookAPIAppDelegate.h"
#import "FacebookAPIViewController.h"

@implementation FacebookAPIAppDelegate

@synthesize window;
@synthesize viewController;
@synthesize _session;

- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}

- (void)dealloc {
[_session release];
[viewController release];
[window release];
[super dealloc];
}

@end

Here in FacebookAPIAppDelegate we have just declared _session variable of type FBSession to keep track of the session and to check if session for current user exists or not.

Append Following code in FacebookAPIViewController.h


#import  
#import "FBConnect/FBConnect.h"
#import "FBConnect/FBSession.h"

@interface FacebookAPIViewController : UIViewController {
FBLoginButton *loginButton;
UIAlertView *facebookAlert;
FBSession *usersession;
NSString *username;
BOOL post;
}

@property(nonatomic,retain) FBLoginButton *loginButton;
@property(nonatomic,retain) UIAlertView *facebookAlert;
@property(nonatomic,retain) FBSession *usersession;
@property(nonatomic,retain) NSString *username;
@property(nonatomic,assign) BOOL post;

- (BOOL)textFieldShouldReturn:(UITextField *)textField;
-(void)getFacebookName;
-(void)postToWall;

@end


Append Following code in FacebookAPIViewController.m

  #import "FacebookAPIViewController.h"
#import "FacebookAPIAppDelegate.h"

#define _APP_KEY @"Your API Key Goes here"
#define _SECRET_KEY @"Your Secrete Key Goes here"

@implementation FacebookAPIViewController
@synthesize loginButton;
@synthesize facebookAlert;
@synthesize usersession;
@synthesize username;
@synthesize post;

- (void)viewDidLoad {
FacebookAPIAppDelegate *appDelegate =
(FacebookAPIAppDelegate *) [[UIApplication
sharedApplication]delegate];
if (appDelegate._session == nil){
appDelegate._session = [FBSession
sessionForApplication:_APP_KEY
secret:_SECRET_KEY delegate:self];
}
if(self.loginButton == NULL)
self.loginButton = [[[FBLoginButton alloc] init] autorelease];
loginButton.frame = CGRectMake(0, 0, 100, 50);
[self.view addSubview:loginButton];
[super viewDidLoad];
}

- (void)dealloc {
[username release];
[usersession release];
[loginButton release];
[super dealloc];
}

- (void)session:(FBSession*)session didLogin:(FBUID)uid {
self.usersession =session;
NSLog(@"User with id %lld logged in.", uid);
[self getFacebookName];
}

- (void)getFacebookName {
NSString* fql = [NSString stringWithFormat:
@"select uid,name from user where uid == %lld",
self.usersession.uid];
NSDictionary* params =
[NSDictionary dictionaryWithObject:fql
forKey:@"query"];
[[FBRequest requestWithDelegate:self]
call:@"facebook.fql.query" params:params];
self.post=YES;
}

- (void)request:(FBRequest*)request didLoad:(id)result {
if ([request.method isEqualToString:@"facebook.fql.query"]) {
NSArray* users = result;
NSDictionary* user = [users objectAtIndex:0];
NSString* name = [user objectForKey:@"name"];
self.username = name;
if (self.post) {
[self postToWall];
self.post = NO;
}
}
}

- (void)postToWall {
FBStreamDialog *dialog = [[[FBStreamDialog alloc] init]
  autorelease];
dialog.userMessagePrompt = @"Enter your message:";
dialog.attachment = [NSString
stringWithFormat:@"{\"name\":\"Facebook Connect for
iPhone\",\"href\":\"http://developers.facebook.com/
connect.phptab=iphone\",\"caption\":\"Caption\",
\"description\":\"Description\",\"media\":[{\"type\":
\"image\",\"src\":\"http://img40.yfrog.com/img40/
5914/iphoneconnectbtn.jpg\",\"href\":
\"http://developers.facebook.com/connect.php?
tab=iphone/\"}],\"properties\":{\"another link\":
{\"text\":\"Facebook home page\",\"href\":
\"http://www.facebook.com\"}}}"];
[dialog show];
}

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

@end

Define API key and Secret key with the keys you received while registering your app on facebook.


#define _APP_KEY @"put your app key over here"
#define _SECRET_KEY @"put your secret key over here"

Validate session variable in ViewDidLoad. If it doesn’t exist then create the same for using API key and Secret key. For that, one needs to conform the protocol FBSessionDelegate in respective header file. Also create a login button using FBLoginButton.

While implementing protocol FBSessionDelegate one needs to implement following mandatory method
view source
print?

-(void)session:(FBSession*)session didLogin:(FBUID)uid

This methos is automatically called when user is logged in using FBConnect SDK.
In this method we get session for that user and it’s uid which unique identifier for that user.

Once FBSession session is avaiable, we can accesss all the APIs provided by Facebook.
For now, we will see how to post user name and status on the facebook wall.

To get Facebook username a request is send in which select query is written to get username using uid.

  NSString* fql = [NSString stringWithFormat:
@"select uid,name from user where uid == %lld", self.usersession.uid];
NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:@"query"];
[[FBRequest requestWithDelegate:self] call:@"facebook.fql.query" params:params];

Override following FBRequestDelegate method to check the reponse of above query.


-(void)request:(FBRequest*)request didLoad:(id)result

The argument result is an array of NSDictionary Objects which contains info for that user as key-value pairs. Retrieve it as follows:

  NSArray* users = result;
NSDictionary* user = [users objectAtIndex:0];
NSString* name = [user objectForKey:@"name"];

Use FBStreamDialog class post message on the facbook wall. A dialog pops up with a message box to post on Wall.


FBStreamDialog *dialog = [[[FBStreamDialog alloc] init] autorelease];
dialog.userMessagePrompt = @"Enter your message:";
dialog.attachment = [NSString stringWithFormat:@"{\"name\":\"Facebook Connect for iPhone\",\"href\":\"http://developers.facebook.com/connect.php?tab=iphone\",\"caption\":\"Caption\",\"description\":\"Description\",\"media\":[{\"type\":\"image\",\"src\":\"http://img40.yfrog.com/img40/5914/iphoneconnectbtn.jpg\",\"href\":\"http://developers.facebook.com/connect.php?tab=iphone/\"}],\"properties\":{\"another link\":{\"text\":\"Facebook home page\",\"href\":\"http://www.facebook.com\"}}}"];
[dialog show];

Now Save project (Command +S). Build and Run Project.

Simulator will look like as follows


 Click on Fconnect Button and Facebook Login Dialog will appear.


Login with your user name and Password . Wait for untill post to Wall Dialog pops up




You can download the source code from here. I hope this will help u in a better way.

NOTE: Some contents of this post are fetched from some other web sources.

Sunday, October 3, 2010

UIActivityIndicator in status bar

spinner status bar To display a UIActivityIndicator use the UIApplication’s property: networkActivityIndicatorVisible.

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

and to disable:

    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

That’s almost all about UIActivityIndicator. More can be found in UIActivityIndicator Class Reference in documentation.

Thursday, September 30, 2010

How to expand cell of a Table View with animation... :)

here is how i am managing this

1. you need an NSMutableArray

the NSMutablearray is the same count as the datasource array for the table

so, you need to populate it with something like this

Code:

self.cellAccessArray = [[NSMutableArray alloc] initWithObjects:@"closed",@"closed",@"closed",@"closed",nil];
[self.cellAccessArray release];

this means we have 4 table rows

now, in your heightForRowAtIndexPath, put this

Code:

if([[self.cellAccessArray object atIndex:indexPath.row] isEqualToString:@"open"])
{
return 140;
}
return 70;

now, to the didSelectRowAtIndexPath

put this


Code:

if([[self.cellAccessArray objectAtIndex:indexPath.row] isEqualToString:@"closed"])
{
[self.cellAccesArray replaceObjectAtIndex:indexPath.row withObject:@"open"];
}
else
{
[self.cellAccesArray replaceObjectAtIndex:indexPath.row withObject:@"closed"];
}

[tableView reloadRowsAtIndexPath:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];


If you want a more Attractive way to do this then click here.

Friday, September 24, 2010

Methods for CUT, COPY n PASTE in any iPhone App.

-(IBAction)cut {
  [self copy];
  textPad.text = @"";
} 
 
-(IBAction)copy {

        NSString *copyString = [[NSString alloc] initWithFormat:@"%@",[textPad text]];
        UIPasteboard *pb = [UIPasteboard generalPasteboard];
        [pb setString:copyString];
}

-(IBAction)paste {
        UIPasteboard *pb = [UIPasteboard generalPasteboard];
        textPad.text = [pb string];
} 

Monday, September 20, 2010

My Camera

This is an App which is useful when u need to develop a Camera App which provides the facility to user to edit image size and crop using a Square Box. To get Source Code click here.

My Compaas

This is an iPhone App which describe the working of Compass in 3gs n upgraded iphones. to download the Source Code click here.

Friday, September 3, 2010

How to create own delegates..... (Protocol methods)

if u want to update any variable or call any method of any class for Eg. Class A). of your project while the control is working in any other class(for Eg. Class B), then you can do it by creating your own delegate/protocol in calling class, and Declare that method in that protocol n define that method in called class.... to elaborate lets see the code.....


Calling.h //First Class

@protocol myDelegate [NSObject]
@optional
- (void) doIt;
@end

@interface Calling :
UIViewController {

id [
myDelegate] delegate;
}

@property(nonatomic, retain) id
[myDelegate] delegate;

@end




Calling.m

#import " Calling.h"

#import " Called.h "

@implementation Calling

@synthesize delegate;

- (void)viewDidLoad {
[super viewDidLoad];

[delegate hideUnhideMenu];
}

@end




Called.h // Class B

@interface Called : UIViewController
[myDelegate] {

}

@end




Called.m

#import " Called.h"

@implementation Called

- (void)viewDidLoad {
[super viewDidLoad];

Calling* obj = [[Calling alloc] init];
obj.delegate = self;
}

- (void)hideUnhideMenu {

//Do your updation here.
}

@end


NOTE: please replace "[" type of brackets with "<". 



for more details about this post click here

Delegate methods to delete rows from a table view.

- (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewCellEditingStyleDelete;
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
// Updates the appearance of the Edit|Done button as necessary.

[super setEditing:editing animated:animated];
[tblName setEditing:editing animated:animated];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView beginUpdates];
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Do whatever data deletion you need to do...
// Delete the row from the data source
//[arrItems removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:YES];
}
[tableView endUpdates];
}

Add Discloserbutton in tableview n do sumthing on click

- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath
{
return UIButtonTypeDetailDisclosure;
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
//Do what you want here.
}

Monday, August 30, 2010

How to customize Alert View

Customize Alert View like...

1. Changing background color of a alert view...
2. Change in Alert View Buttons.. etc.

UIAlertView *theAlert = [[[UIAlertView alloc] initWithTitle:@"My Alert"
message: nil delegate:self cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Button1", @"Button2", @"Button3", nil] autorelease];
[theAlert show];

//Set View of Button Cancel at index 1 in AlertView.
[[[theAlert subviews] objectAtIndex:1] setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"btnCancelBG.png"]]];
[[[theAlert subviews] objectAtIndex:1] setShadowColor:[UIColor clearColor]];

//Set View of Button at index 2 in AlertView.
[[[theAlert subviews] objectAtIndex:2] setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"button1.png"]]];
[[[theAlert subviews] objectAtIndex:2] setShadowColor:[UIColor clearColor]];
[[[theAlert subviews] objectAtIndex:2] setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];

//Set View of Button at index 3 in AlertView.
[[[theAlert subviews] objectAtIndex:3] setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"button2.png"]]];
[[[theAlert subviews] objectAtIndex:3] setShadowColor:[UIColor clearColor]];
[[[theAlert subviews] objectAtIndex:3] setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];

//Set View of Button at index 4 in AlertView.
[[[theAlert subviews] objectAtIndex:4] setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"button3.png"]]];
[[[theAlert subviews] objectAtIndex:4] setShadowColor:[UIColor clearColor]];
[[[theAlert subviews] objectAtIndex:4] setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];

UILabel *theTitle = [theAlert valueForKey:@"_titleLabel"];
[theTitle setFont:[UIFont fontWithName:@"Helvetica" size:16]];
[theTitle setTextAlignment:UITextAlignmentLeft];

UIImage *theImage = [UIImage imageNamed:@"alertBG.png"];
CGSize theSize = [theAlert frame].size;

UIGraphicsBeginImageContext(theSize);
[theImage drawInRect:CGRectMake(0, 0, theSize.width, theSize.height)];
theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

[[theAlert layer] setContents:[theImage CGImage]];






to get a running Sample Code Click here...

Sunday, August 29, 2010

To find any object in a view

here I am searching for a button in a AlertView.


for (UIView *v in [myAlertView subviews]) {
if ([v isKindOfClass:[UIButton class]]) {
//IF I AM THE RIGHT BUTTON
[v addSubview:myUIImageView];
}
}

Animation: Move an object

Show something moving across the screen. Note: this type of animation is "fire and forget" -- you cannot obtain any information about the objects during animation (such as current position). If you need this information, you will want to animate manually using a Timer and adjusting the x&y coordinates as necessary.



CABasicAnimation *theAnimation; theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.translation.x"]; theAnimation.duration=1; theAnimation.repeatCount=2; theAnimation.autoreverses=YES; theAnimation.fromValue=[NSNumber numberWithFloat:0]; theAnimation.toValue=[NSNumber numberWithFloat:-60]; [view.layer addAnimation:theAnimation forKey:@"animateLayer"];

Wednesday, August 4, 2010

How to Jail Break an iphone....

Posted by Alias420

These are step by step instructions on how to use QuickPwn 1.1 for Apple Mac OSX to jailbreak your 2.1 iPhone or iPhone 3G.

Step One
Create a folder on your desktop called Pwnage

Step Two
Download QuickPwn 1.1 from here and place it in the Pwnage folder. Likewise, download the latest 2.1 firmware from below and place it in the same folder.

iPhone 2.1 ipsw Download
iPhone 3G 2.1 ipsw Download


Step Three
Now double click to mount the QuickPwn [QuickPwn_1.1.dmg] archive that you downloaded above. Then drag the QuickPwn application into the Pwnage folder you created on your desktop.

Step Four
Now double click the icon to launch QuickPwn from your Pwnage folder.

Step Five
Click OK to accept the copyright notice.

Step Six
Connect your iPhone or iPhone 3G into the computer when asked, then click OK.

Step Seven
QuickPwn will now automatically detect the device that you connected!

Step Eight
QuickPwn will now attempt to find the latest firmware for this device

Step Nine
You will be asked if you would like to replace the original boot and recovery logos on your iPhone. Select Yes or No to continue.

Step Ten
QuickPwn will now build your custom IPSW.

Step Eleven
You will be prompted to enter your username and password. After doing this, then click OK.

Step Twelve
QuickPwn will now guide you on how to put your iPhone into DFU mode. Pay attention and do exactly as QuickPwn directs you. First, turn off the device.

Next, you will be prompted to hold both the Home and Power buttons for 10 seconds.

Finally, you will let go of the power button and continue holding down the Home button for another 10 seconds.

Step Thirteen
QuickPwn will now begin sending information to your iPhone.

Step Fourteen
You will notified that QuickPwn is modifying your iPhone. The process will take some time and will cause the iPhone to reboot. Do not do anything until the process has completed.

Step Fifteen
After your iPhone has rebooted it will be jailbroken and have both Cydia and Installer on the Springboard. Congratulations!

Tuesday, August 3, 2010

How to adjust height of Status bar or Hide the status bar...


//Set height
[UIHardware _setStatusBarHeight:0.0f];

//Set for a limited time
[self setStatusBarMode:2 duration:0.0f];

//hide status bar
[self setStatusBarHidden:YES animated:NO];

Wednesday, July 14, 2010

Friday, July 9, 2010

Location Manager Delegate methods.....

-(IBAction)btn_Clicked:(id)sender
{
if(locationManager.locationServicesEnabled)
{
[spinner startAnimating];
btn.enabled = NO;
[locationManager startUpdatingLocation];
}
}

#pragma mark -
#pragma mark Geo Points methods

//It will be called whenever the device is able to detect GPS locations.....

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if(newLocation != nil)
appDelegate.currentLocation = newLocation;
else
appDelegate.currentLocation = oldLocation;

[locationManager stopUpdatingLocation];
btn.enabled = YES;
[spinner stopAnimating];

UIMyViewController *myViewController = [[UIMyViewController alloc] initWithNibName:@"MyView" bundle:nil];
[self.navigationController pushViewController:myViewController animated:YES];
[stateViewController release];
}


//It will be called when device will fail to get GPS location and will show a popup with "Don't Allow" and "Ok" button.....

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
[locationManager stopUpdatingLocation];
btn.enabled = YES;
[spinner stopAnimating];

UIMyViewController *myViewController = [[UIMyViewController alloc] initWithNibName:@"MyView" bundle:nil];
[self.navigationController pushViewController:myViewController animated:YES];
[stateViewController release];

/*if (error.code == kCLErrorDenied)
{
// User denied access to location service
printf("\n\n Don't Allow Clicked.");
}
else if (error.code == kCLErrorLocationUnknown)
{
// User denied access to location service
printf("\n\n OK Clicked.");
}
else if (error.code == kCLErrorNetwork)
{
// User denied access to location service
printf("\n\nmy error kCLErrorNetwork.");
}
else if (error.code == kCLErrorHeadingFailure)
{
// User denied access to location service
printf("\n\nmy error kCLErrorHeadingFailure.");
}*/
}

How to rotate compaas needle manually....

#define RadiansTodegrees(Y) ( 180.0* Y / 3.14)

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
theEndPoint = [touch locationInView:self.view];
if((theEndPoint.x>My_Compass.frame.origin.x && theEndPoint.y>My_Compass.frame.origin.y) && (theEndPoint.x {
float Centre_X = My_Compass.frame.origin.x + (My_Compass.frame.size.height/2);
float Centre_Y = My_Compass.frame.origin.y + (My_Compass.frame.size.width/2);

float dx=theEndPoint.x-Centre_X;
float dy=theEndPoint.y-Centre_Y;

double angle=atan2(dy,dx);
double br = RadiansTodegrees(angle);

CGAffineTransform rotate = CGAffineTransformMakeRotation(((br+90)/180)*3.14);
[Niddel setTransform:rotate];

}

}

Wednesday, July 7, 2010

How to validate an email id..?

Way 1.

NSString *email = textFieldemail.text;
NSString *emailRegEx =
@"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
@"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
@"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
@"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
@"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
@"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
@"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";

NSPredicate *regExPredicate =
[NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
BOOL myStringMatchesRegEx = [regExPredicate evaluateWithObject:email];


if(!myStringMatchesRegEx)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"email" message:@"Email id is invalid, please provide a valid email id." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
[self prepareHmlDataAndSendEmail];

Way 2.

if (! (([txtMailId.text rangeOfString:@"@"].location != NSNotFound) && ([txtMailId.text rangeOfString:@"."].location != NSNotFound) && [txtMailId.text rangeOfString:@"@"].location < [txtMailId.text rangeOfString:@"."].location ) )
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"email" message:@"Email id is invalid, please provide a valid email id." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
[self prepareHmlDataAndSendEmail];

Way 3.
NSArray *validateAtSymbol = [txtLoginId.text componentsSeparatedByString:@"@"];
NSArray *validateDotSymbol = [txtLoginId.text componentsSeparatedByString:@"."];
if(([validateAtSymbol count] != 2) || ([validateDotSymbol count] < 2))
{      
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:@"Invalid EMail Address" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok", nil];
[alertView show];
[alertView release];
}

Thursday, July 1, 2010

Location Manager for compass movment n to call methods on changing angle from one quater to another.

class.h

@interface class : UIViewController
{
CLLocationManager *locationManager;
}

class.m


#pragma mark -
#pragma mark Geo Points methods

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if(newLocation != nil)
currentLocation = newLocation;
else
currentLocation = oldLocation;

[self btn_POIStartClicked];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
/*NSString *msg=[NSString stringWithFormat:@"New magnetic heading: %f and New true heading: %f. ",newHeading.magneticHeading,newHeading.trueHeading];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Info" message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert = nil;
NSLog(@"New true heading: %f", newHeading.trueHeading);
NSLog(@"New magnetic heading: %f", newHeading.magneticHeading);*/
int angle = newHeading.magneticHeading;
CGAffineTransform rotate = CGAffineTransformMakeRotation( newHeading.magneticHeading/180*3.14 );
[compassView setTransform:rotate];

if(oldAngel != (angle/90))
{
switch (angle/90)
{
case 0:
{

}
break;
case 1:
{

}
break;
case 2:
{

}
break;
case 3:
{

}
break;
}
}
}

Customize view on Camera View.

STEPS:

step 1. Load the xib which will contain camera view...
step 2. Now load camera on that xib.
step 3. Now load the view (addSubView) on camera.cameraOverlayView.

camera.m


//********************************* CAMERA VIEW CODE*******************************
camera = [[UIImagePickerController alloc] init];
camera.view.backgroundColor = [UIColor clearColor];
overView.frame = CGRectMake(0,44,320,416);
nvgView.frame = CGRectMake(0,0,320,44);

// [camera.view addSubview:overView];
// [camera.view addSubview:nvgView];


// Hide Apple's UI.
#if TARGET_IPHONE_SIMULATOR
camera.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
camera.navigationBarHidden = YES;
camera.toolbarHidden = YES;

[camera.view addSubview:overView];
[camera.view addSubview:nvgView];

#elif TARGET_OS_IPHONE
camera.sourceType = UIImagePickerControllerSourceTypeCamera;
camera.showsCameraControls = NO;
camera.navigationBarHidden = YES;
camera.toolbarHidden = YES;
camera.wantsFullScreenLayout = YES;
camera.cameraViewTransform = CGAffineTransformScale(camera.cameraViewTransform, 2.0f, 2.0f);

// Add the view to be overlaid
//camera.cameraOverlayView = overView;
[camera.cameraOverlayView addSubview:flipView];
[camera.cameraOverlayView addSubview:nvgView];

#endif

// Show the camera's view as a modal dialog.
[self presentModalViewController:camera animated:YES];
[self.view addSubview:camera.view];
//********************************** CAMERA VIEW END*******************************

Page controller with scroll view (first xib in another xib)

outer.h

@interface outer : UIViewController {

NSInteger kNumberOfPages;
NSInteger selectedPage;
NSArray* arrRepList;

IBOutlet UIPageControl* pageControl;
IBOutlet UIScrollView* scrollView;

NSMutableArray *viewControllers;
//BOOL pageControlUsed;
}

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

- (IBAction)changePage:(id)sender;

@end


outer.m

@interface outer (PrivateMethods)

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

@end

@implementation outer

- (void)viewDidLoad {
[super viewDidLoad];
kNumberOfPages = 7;
self.title = @"Outer XIB";

// 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 = selectedPage;
[pageControl setFrame:CGRectMake(pageControl.frame.origin.x,pageControl.frame.origin.y,pageControl.frame.size.width,pageControl.frame.size.height*(3.0/4.0))];
//CGRect tmp=CGRectMake(320*selectedPage, 0,320,305 );
//[scrollView scrollRectToVisible:tmp animated:YES];
[self changePage:nil];

}

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

// replace the placeholder if necessary
UIRepDetailsViewController *controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null]) {
controller = [[UIRepDetailsSubView alloc] initWithPageNumber:page andRepList:arrRepList];
[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 - 2];
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
[self loadScrollViewWithPage:page + 2];
// A possible optimization would be to unload the views+controllers which are no longer visible
}

// 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 - 2];
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
[self loadScrollViewWithPage:page + 2];
// 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;
}





inner.h

/* all declarations */
int pageNumber;
NSArray* arrRepList;

inner.m

static NSArray *__pageControlColorList = nil;

@implementation inner

// Creates the color list the first time this method is invoked. Returns one color object from the list.
+ (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 andRepList:(NSArray*) repList{
if (self = [super initWithNibName:@"RepDetailsSubView" bundle:nil]) {
pageNumber = page;
arrRepList = repList;
}
return self;
}

Keyboard adjustment while typing in a textfield

- (void)textViewDidBeginEditing:(UITextView *)textView
{
[self setViewMovedUp:YES];
}

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

- (void)setViewMovedUp:(BOOL)movedUp{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
// Make changes to the view's frame inside the animation block. They will be animated instead
// of taking place immediately.
CGRect rect = self.view.frame;
if (movedUp){
// If moving up, not only decrease the origin but increase the height so the view
// covers the entire screen behind the keyboard.
//rect.origin.y -= kOFFSET_FOR_KEYBOARD;
//rect.size.height += kOFFSET_FOR_KEYBOARD;
if(rect.origin.y ==0)
rect.origin.y = self.view.frame.origin.y - 165;
}
else{
// If moving down, not only increase the origin decrease the height.
//rect.origin.y += kOFFSET_FOR_KEYBOARD;
//rect.size.height -= kOFFSET_FOR_KEYBOARD;
if(rect.origin.y <0)
rect.origin.y = self.view.frame.origin.y + 165;
}

self.view.frame = rect;
[UIView commitAnimations];
}

How to Change String format from "48821869.89" to "48,821,869.89"

-(NSString*)convertStringInCommaFormat:(NSString*) inputStr
{
double strInDouble = [inputStr doubleValue];
int strInInt = strInDouble;
float strFloatingPart = strInDouble - strInInt;
NSString* temp = [NSString stringWithFormat:@"%d",strInInt];
int check = [temp length] % 3;

NSString* strFinal= @"";
if(check != 0)
{
NSString* ch =[temp substringWithRange:NSMakeRange(0, check)];
strFinal = [strFinal stringByAppendingString:[NSString stringWithFormat:@"%@,",ch]];
}
for(int k = 0 ; k<[temp length]/3 ; k++)
{
NSString* ch =[temp substringWithRange:NSMakeRange(check, 3)];
strFinal = [strFinal stringByAppendingString:[NSString stringWithFormat:@"%@,",ch]];
check = check+3;
}

NSString* final = [strFinal substringWithRange:NSMakeRange(0, [strFinal length] - 1)];
NSString* strTemp = [NSString stringWithFormat:@"%0.2f",strFloatingPart];
NSString* strAfterDot = [strTemp substringWithRange:NSMakeRange(1, [strTemp length] - 1)];
final = [final stringByAppendingString:[NSString stringWithFormat:@"%@",strAfterDot]];

return final;
}

Sunday, June 27, 2010

Picker View Methods

#pragma mark -
#pragma mark UIPickerViewDelegate methods

- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSString *str = [myArray objectAtIndex:row];
return str;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
UIMyViewController *myViewController = [[UIMyViewController alloc] initWithNibName:@"MyView" bundle:nil];
[self.navigationController pushViewController:myViewController animated:YES];
[myViewController release];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return /*no of Components (Partitions of Picker)*/;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [myArray count];
}

Table View Methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return /*no of sections*/;
}

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

return /*hight in float*/;
}

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

return [myArray count];

}

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

static NSString *CellIdentifier = @"Cell";

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

// Customize the Cell.
cell.selectionStyle = UITableViewCellSelectionStyleGray;
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
cell.textLabel.text = [myArray objectAtIndex: indexpath.row];
cell.textLabel.textAlignment = UITextAlignmentRight;
[cell.textLabel setFont:[UIFont fontWithName:@"Helvetica" size:18 ]];

return cell;
}

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

UIMyViewController* myViewController = [[UIMyViewController alloc] initWithNibName: @"MyView" bundle: nil];
[self.navigationController pushViewController: myViewController animated: YES];
[myViewController release];
}