Friday, December 17, 2010

to check app running first time or not on iphone

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if (![prefs objectForKey:@"alert"]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"this is 1st time" message:@"Some description"
delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"alert"];
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@" this is 2nd time!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release];
NSLog(@" DEJA VU");


[[NSUserDefaults standardUserDefaults] synchronize];

Wednesday, October 20, 2010

IPhone GPS

- (CLLocationManager *)locationManager {
if (locationManager != nil) {
return locationManager;

locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;

return locationManager;

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {

//[locationMeasurements addObject:newLocation];


#pragma mark lat

NSString *lat = [[NSString alloc] initWithFormat:@"%0.3f", newLocation.coordinate.latitude];

// NSLog(@"1l89899898ee");

NSString *lonn = [[NSString alloc] initWithFormat:@"%0.3f", newLocation.coordinate.longitude];

//latitudeString =newLocation.coordinate.latitude;
//NSLog(@"lat is %@", lat);
//self.myLatitude = latitudeString;
//[latitudeString release];
#pragma mark long


NSUserDefaults *alat = [NSUserDefaults standardUserDefaults];
[alat setObject:lat forKey:@"Latitude"];

NSUserDefaults *along = [NSUserDefaults standardUserDefaults];
[along setObject:lonn forKey:@"Longitude"];

//NSLog(@"lon fgfgfgfg is %@", lonn);



- (void)locationManager: (CLLocationManager *)manager didFailWithError: (NSError *)error
NSLog(@"Location Error: %@",error);
switch([error code])
case kCLErrorNetwork: // general, network-related error
NSLog(@"please check your network connection or that you are not in airplane mode");
case kCLErrorDenied:{
NSLog(@"user has denied to use current Location");
NSLog(@"unknown network error");
[manager stopUpdatingLocation];

- (void)starte {

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

NSLog(@" thread stretr ");
[[self locationManager] startUpdatingLocation];

NSLog(@" main tgreas point is %@",latitudeString);

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// getting an NSString
NSString *Latu = [prefs stringForKey:@"Latitude"];
NSLog(@" new lati is %@",Latu);

NSUserDefaults *alongs = [NSUserDefaults standardUserDefaults];
NSString *Longu = [alongs stringForKey:@"Longitude"];

NSLog(@" new longu is %@",Longu);

#pragma mark APP iD

#pragma mark sysID
NSString *sysID=[[UIDevice currentDevice] uniqueIdentifier];
NSLog(@" ID IS %@",sysID);

NSString *ip=@"ip";
NSString* OS=@"3";

//NSLog(@"latitude is %@", myString );

NSString *AppID=[NSString stringWithFormat:@"%@|%@|%@|%@|%@",Latu,Longu,sysID,ip,OS];
NSLog(@" MY APPLE OD IS %@",AppID );

NSUserDefaults *aDD = [NSUserDefaults standardUserDefaults];
[aDD setObject:AppID forKey:@"AppID"];


[pool drain];
[pool release];


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

[[self locationManager] startUpdatingLocation];
[self performSelectorInBackground:@selector(starte) withObject:nil];

Monday, October 18, 2010

Flip navigation controller

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration: 1];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:YES];
[self.navigationController pushViewController:atab animated:YES];
//[self.navigationController pushViewController:myViewController animated:NO];
[UIView commitAnimations];

Friday, October 15, 2010

change navigation bar to black

self.navigationController.navigationBar.barStyle = UIBarStyleBlack;

Thursday, October 14, 2010

remove charcater from string

lets say you have @"hello" now ir order to get ello you can do this
NSString *newStr = [myString substringWithRange:NSMakeRange(1, [myString length] - 1)];

Tuesday, October 12, 2010

AES encrypt and dec

download file from

and use them like this

NSString *passphrase = @"1234567812345678";
NSStringEncoding myEncoding = NSASCIIStringEncoding;

NSString *alphaStringPlain = @"hello";

NSData *alphaDataPlain = [alphaStringPlain dataUsingEncoding:myEncoding];

NSData *alphaDataCypher = [alphaDataPlain AESEncryptWithPassphrase:passphrase];
NSString *alphaStringCypher = [[NSString alloc] initWithData:alphaDataCypher encoding:myEncoding];

NSLog(alphaStringCypher); // encode

NSData *zCypher = [alphaDataCypher AESDecryptWithPassphrase:passphrase];
NSString *Cypher = [[NSString alloc] initWithData:zCypher encoding:myEncoding];

//NSData *zCypher = [alphaStringCypher AESDecryptWithPassphrase:passphrase];

NSLog(@" hua kya decode %@",[Cypher dataUsingEncoding:NSUTF8StringEncoding]);// decode

deatil code

Tuesday, September 28, 2010

JSON parser

{ "name":{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
"type": "home",
"number": "212 555-1234",
"type": "fax",
"number": "646 555-4567",
"type": "sun",
"number": "646 555-4567",


//////////////////////// this is how we parse this JSON

- (void)viewDidLoad {
jsonArray= [[NSMutableArray alloc] init] ;
[super viewDidLoad];

responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@""]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
label.text = [NSString stringWithFormat:@"Connection failed: %@", [error description]];
- (void)addRowToLogWindow:(id)data {

label.text = [NSString stringWithFormat:@"Adding data: %@%@", data, label.text]; // adding new row + 2x new line "


- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];

NSError *error;
SBJSON *json = [[SBJSON new] autorelease];

NSDictionary *data = (NSDictionary *) [json objectWithString:responseString error:nil];

NSDictionary *menu = (NSDictionary *) [data objectForKey:@"name"];

NSArray *items = (NSArray *) [menu objectForKey:@"phoneNumber"];

int ndx;

for (ndx = 0; ndx< items.count; ndx++) {

stream = (NSDictionary *)[items objectAtIndex:ndx];

NSLog(@"This is the title of a stream: %@", [stream valueForKey:@"type"]);
[jsonArray addObject:stream];


NSLog(@" aray is %@",jsonArray);
NSLog(@" sterab is %@",[stream valueForKey:@"home"]);

[tableview reloadData];

NSLog(@" json coutn is %d",[jsonArray count]);

NSString *luckyNumbers = [json objectWithString:responseString error:&error];
[responseString release];

if (luckyNumbers == nil)
label.text = [NSString stringWithFormat:@"JSON parsing failed: %@", [error localizedDescription]];
else {
NSMutableString *text = [NSMutableString stringWithString:@"Lucky numbers:\n"];

label.text = text;

#pragma mark tabel

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

//if (searching)
//return 1;

return 1;

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

NSLog(@" 43534535353 %d",[jsonArray count]);
return [jsonArray count];


//////////// WORKING CELL BIGGER SIZE CODE///////////

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

/* if(indexPath.row == 0)

return 85;


return 55;


////////////// ENDS HERE/////////////

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//UITableView *tableView;
UITableViewCell *cell;
static NSString *CellIdentifier = @"Cell";

//self.tableView.frame = CGRectMake(0,searchBar.bounds.size.height,320,480);

cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil ) {

NSLog(@" inside");
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];

mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(10.0, 5.0, 220.0, 15.0)] autorelease];

mainLabel.tag =33;

// mainLabel.font = [UIFont systemFontOfSize:14.0];
[mainLabel setFont:[UIFont boldSystemFontOfSize:[UIFont smallSystemFontSize]]];

mainLabel.textAlignment = UITextAlignmentLeft;

mainLabel.textColor = [UIColor blackColor];
mainLabel.highlightedTextColor = [UIColor greenColor];

//mainLabel.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight;

[cell.contentView addSubview:mainLabel];
mainLabel.backgroundColor=[UIColor clearColor];


mainLabel.text = [[jsonArray objectAtIndex:indexPath.row] objectForKey:@"number"];
NSLog(@" dicst 5@",stream);
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
return cell;


Monday, September 13, 2010

Delegates Concept

delegate performs methods on behalf of another object. A Table View doesn't know what to do when you pick an item in the list. Instead, it has to ask the delegate object a question, specifically, didSelectRowAtIndexPath. The only information the tableview knows is which section and row the user tapped. So the table view gives this information to the delegate object by essentially saying that "Hey, the user tapped Row 4 in Section 0. Do something."

The delegate object finds the didSelectRowAtIndexPath method and executes the code inside.

There are lots of Delegate methods for many different objects. For instance, the Text Field object can't do anything on its own. Instead, it uses a delegate to perform actions. If you press the enter key on the on screen keyboard, the text field asks the delegate object to perform a specific method, textFieldShouldReturn. If the delegate you set for your text field does not have a textFieldShouldReturn method, the text field will not know what to do when you press the enter button.

Wednesday, August 18, 2010

multiple annotation map

- (void)viewDidLoad
locationManager=[[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//Start the compass updates.
[locationManager startUpdatingHeading];
[[self locationManager] startUpdatingHeading];
[[self locationManager] startUpdatingLocation];

[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];

MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } }; = 1.30;//41.902245099708516; = 103.8;//12.457906007766724;
region.span.longitudeDelta = 0.01f;
region.span.latitudeDelta = 0.01f;
[mapView setRegion:region animated:YES];

[mapView setDelegate:self];

MyAnnotation *ann = [[MyAnnotation alloc] init];
ann.title = @"Rome";
ann.subtitle = @"San Peter";
ann.coordinate =;
//[mapView addAnnotation:ann];

/// one more annt
//My own Annotation
MKCoordinateRegion SecondRegion; = 1.301; = 103.81;

MyAnnotation *aSecondAnnotation = [[MyAnnotation alloc] init];
aSecondAnnotation.title = @"Second Annotation";

//By the way, this line doesn’t work, everything is still in the same line :(
aSecondAnnotation.subtitle = @"clerqkey";
aSecondAnnotation.coordinate =;

//// 2 more

MKCoordinateRegion SecondRegiona; = 1.31; = 103.9;

MyAnnotation *aSecondAnnotationa = [[MyAnnotation alloc] init];
aSecondAnnotationa.title = @"3rd Annotation";

//By the way, this line doesn’t work, everything is still in the same line :(
aSecondAnnotationa.subtitle = @"ret";
aSecondAnnotationa.coordinate =;


NSArray *Annotations = [NSArray arrayWithObjects:ann,aSecondAnnotation,aSecondAnnotationa,nil];

[mapView addAnnotations:Annotations];

[super viewDidLoad];
- (void)locationManager:(CLLocationManager *) manager didUpdateHeading:(CLHeading *) newHeading {
NSLog(@"New magnetic heading: %f", newHeading.magneticHeading);
NSLog(@"New true heading: %f", newHeading.trueHeading);


- (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView
for (id currentAnnotation in mapView.annotations) {
[mapView selectAnnotation:currentAnnotation animated:YES];
- (MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id )annotation
MKPinAnnotationView *pinView = nil;
[[self locationManager] startUpdatingHeading];
if(annotation != mapView.userLocation)
static NSString *defaultPinID = @"";
pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if ( pinView == nil )
pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];

pinView.pinColor = MKPinAnnotationColorPurple;
pinView.canShowCallout = YES;
pinView.animatesDrop = YES;
[mapView.userLocation setTitle:@"I am here"];

return pinView;

Thursday, August 12, 2010

unzip data from web

NSString *aDirectory =
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

NSFileManager *fileManager= [NSFileManager defaultManager];

NSString* filePath = [NSString stringWithFormat:@"%@/", aDirectory];
NSString* updateURL = @"http://localhost/";
NSLog(@"Checking update at : %@", updateURL);
NSData* updateData = [NSData dataWithContentsOfURL: [NSURL URLWithString: updateURL] ];

[fileManager createFileAtPath:filePath contents:updateData attributes:nil];

ZipArchive *zipArchive = [[ZipArchive alloc] init];

if([zipArchive UnzipOpenFile:filePath]) {

if ([zipArchive UnzipFileTo:aDirectory overWrite:YES]) {
//unzipped successfully
NSLog(@"Archive unzip Success");
[fileManager removeItemAtPath:filePath error:NULL];
} else {
NSLog(@"Failure To Unzip Archive");

} else {
NSLog(@"Failure To Open Archive");

[zipArchive release];

NSLog(@"string text is %@",filePath);

Tuesday, August 10, 2010

saving locaaly and update data from web

#pragma mark save file locally

NSString *applicationDocumentsDir =
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:@"sample1.cfg"];

NSURL *instructionsURLd = [[NSURL alloc] initFileURLWithPath:filePath];
NSData *dataXML = [NSData dataWithContentsOfURL:instructionsURLd];

[dataXML writeToFile:storePath atomically:YES];

// NSLog(@"matrix path %@",applicationDocumentsDir);
//NSLog(@"neo path %@",storePath);

#pragma mark update
// http://localhost/update.cfg

//NSData *dataXML = [NSData dataWithContentsOfURL:instructionsURLd];

NSURL *urlf = [[NSURL alloc] initWithString:@"http://localhost/update.cfg"];
dataXML = [NSData dataWithContentsOfURL:urlf];

NSMutableData *file = [[NSMutableData alloc] initWithContentsOfFile:storePath];
[file appendData:dataXML];
[file writeToFile:storePath atomically:YES];

Friday, August 6, 2010

Dynamic buttons and method on them

#pragma mark load filePath
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"tabs" ofType:@"cfg"];
if (filePath) {

NSString *myText = [NSString stringWithContentsOfFile:filePath];

NSMutableArray *a1 = [[NSMutableArray alloc] init];
[a1 addObjectsFromArray:[myText componentsSeparatedByString:@"\n"]];

[a1 addObject:myText];

NSUInteger i;
for (i = 1; i <= [a1 count]-1; i++)

NSString *urlE=[a1 objectAtIndex:1];
NSLog(@"url is %@",urlE);

#pragma mark buttons
CGRect frame = CGRectMake(curXLoc, 10, 60, 30);
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = frame;
[button setImage:[UIImage imageNamed:@"tab2.png"] forState:UIControlStateNormal];
[button setTitle:(NSString *)@"new button" forState:(UIControlState)UIControlStateNormal];
[button addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
curXLoc += (kScrollObjWidth1);
[self.view addSubview:button];



NSLog(@"new button clicked!!!");
if (sender.tag == 1) {
if (sender.tag == 2) {

Tuesday, July 27, 2010

double tap

float distance;
if([touches count] == 2) {
// Order touches so they're accessible separately
NSMutableArray *touchesArray = [[[NSMutableArray alloc]
initWithCapacity:2] autorelease];
for(UITouch *aTouch in touches) {
[touchesArray addObject:aTouch];
UITouch *firstTouch = [touchesArray objectAtIndex:0];
UITouch *secondTouch = [touchesArray objectAtIndex:1];

// Do math
CGPoint firstPoint = [firstTouch locationInView:[firstTouch view]];
CGPoint secondPoint = [secondTouch locationInView:[secondTouch view]];
distance = sqrtf((firstPoint.x - secondPoint.x) *
(firstPoint.x - secondPoint.x) +
(firstPoint.y - secondPoint.y) *
(firstPoint.y - secondPoint.y));

show image in center of table view

CGRect frame;

frame= CGRectMake(230 ,50, 50, 50);
UIImageView * myImageView = [[UIImageView alloc]init];
myImageView.image = [UIImage imageNamed:@"bowl.png"];
//cell.imageView.image= [UIImage imageNamed:@"bowl.png"];

myImageView.frame = frame;
//UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bowl.png"]];
addSubview: myImageView];
[myImageView release];

Thursday, July 22, 2010


gcc -c test.c
$ gcc test.c
$ gcc test.c -o a.out
$ ./a.out

thats it HAPPY CODING :-)

Wednesday, July 21, 2010

How to Debug an iPhone App Crash, Part 1: EXC_BAD_ACCESS

1. Run Build and Analyze: This kind of Build is very good at finding retain/release bugs. Take a good look at everything it flags.
2. Even better, run scan-build. I did a test recently, and found that some common errors are off by default in Build and Analyze that can be turned on in scan-build.
3. Choose Run > Enable Guard Malloc in the menu, and then re-run your application. This finds a whole class of buffer overrun issues. If this detects it, you’ll see a better error in the console.
4. You can instruct the compiler to ignore release calls and then report if anyone is sending messages to objects that would have been deallocated. This results in much better errors in the Console if it detects them.
5. Valgrind is the gold standard for finding memory bugs on Linux, and here’s a way to get it working in the iPhone Simulator.

Thanks to

Friday, July 16, 2010

Adding images to map Annotation

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:
(id )annotation {
if (annotation == mapView.userLocation) return nil;

UIImage *anImage = nil;
if([[annotation title] isEqualToString:@"type1"])
anImage=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"type1.png" ofType:nil]];
else if([[annotation title] isEqualToString:@"type2"])
anImage=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"type2.png" ofType:nil]];
else if([[annotation title] isEqualToString:@"type3"])
anImage=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"type3.png" ofType:nil]];
else if([[annotation title] isEqualToString:@"type4"])
anImage=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"type4.png" ofType:nil]];

MKAnnotationView *anView=(MKAnnotationView*)[mapView

anView=[[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"annotation"] autorelease];
anView.image = anImage;
anView.rightCalloutAccessoryView=[UIButton buttonWithType:UIButtonTypeDetailDisclosure];
return anView;

Thursday, July 8, 2010

pasing string value

statement "SELECT * FROM wateat_tbl where name like '%love%' or desc like '%love%'"
mixing SQL qurey + user input in one string

NSString* SQL_statement = [NSString stringWithFormat:@"SELECT * FROM wateat_tbl where name like '%%%@%%' or desc like '%%%@%%'", myStringPrt2, myStringPrt2];

const char *sqlStatement = [SQL_statement UTF8String]; // string to char need UTF8

Thursday, July 1, 2010

add images to nav bar

UIImage *image = [UIImage imageNamed: @"Enjoy TopBar1.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage: image];

self.navigationItem.titleView = imageView;

Wednesday, June 30, 2010

pointer to integer

If you get the error “warning:comparison between pointer and integer”, odds are you are thinking right, but implementing your comparison wrong.

ur doin it wrong

if(count == 2) {

the right way

if([count intValue] == 2) {

Tuesday, June 29, 2010

saving xml locally

NSURL *url = [[NSURL alloc] initWithString:@"http:/xml.php"];

NSData *data = [NSData dataWithContentsOfURL:url];
NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:@"icellxml.php"];

NSLog(@"new xml %@",storePath );

// write to file atomically (using temp file)
[data writeToFile:storePath atomically:TRUE];

NSLog(@" saved data is %@",storePath);

// NSData *data = [NSData dataWithBytes:ptr length:len]; to get back


NSFileManager *fileManager = [NSFileManager defaultManager];
if([fileManager fileExistsAtPath:storePath]) {
//open it and read it
NSLog(@"data file found. reading into memory");

} else {
NSLog(@"no file found. creating empty array");



NSFileManager *fileManager = [NSFileManager defaultManager];
if([fileManager fileExistsAtPath:storePath]) {
//open it and read it
NSLog(@"data file found. reading into memory");

NSURL *urla = [[[NSURL alloc] init] fileURLWithPath:storePath];

storePath = [storePath stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

NSString *urlb = [[NSURL fileURLWithPath:storePath] absoluteString];

NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSUserDomainMask, YES
NSString *documentsDirectory = [paths objectAtIndex:0];

NSURL *urlc = [NSURL fileURLWithPath:[documentsDirectory
stringByAppendingString:@"/icellxml1.php" ]];

NSLog(@"welcome %@",documentsDirectory );
NSLog(@"werkgwkerwekwegrw %@",urlc);

NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:urlc];

//Initialize the delegate.

XMLParser *parser = [[XMLParser alloc] initXMLParser];

//Set delegate

[xmlParser setDelegate:parser];

//Start parsing the XML file.

BOOL success = [xmlParser parse];

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(@"DAM DAM DAM !!!");

Monday, June 28, 2010

pull data from string

lets say locationString = 1,2,3,4

NSLog(@" GEO MAP is %@",locationString);

//NSString *myData = [NSString stringWithContentsOfFile:myPath];
NSArray *posArray = [[NSArray alloc] initWithArray:[locationString componentsSeparatedByString:@","]];
NSLog(@"count = %d",[posArray count]);
NSLog(@"first one = %f", [[posArray objectAtIndex:2] floatValue]);
NSLog(@"2nd one = %f", [[posArray objectAtIndex:3] floatValue]);

output will be 3,4

getting lati and longi

theAddress = [addressInput.text stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSString *urlString = [NSString stringWithFormat:@"",
NSString *locationString = [[[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:urlString]] autorelease];

Sunday, June 27, 2010

saving and retreving data

/// setting dic
NSUserDefaults *saveDict = [NSUserDefaults standardUserDefaults];
[saveDict setObject:geotext forKey:@"keyToLookupString"];

// getting dic

NSUserDefaults *gete = [NSUserDefaults standardUserDefaults];

// getting an NSString
NSString *myString = [gete stringForKey:@"keyToLookupString"];
NSLog(@" this output is %@",myString);

Thursday, June 24, 2010

sending image and text to server

NSString *uTitle=text.text;
NSString *uMessage=myTextView.text;
NSData *imageData = UIImageJPEGRepresentation(imageView.image, .9);
NSString *post =[[NSString alloc] initWithFormat:@"&title=%@&message=%@&imagedetal=%@",uTitle,uMessage,imageData];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];


// setting up the URL to post to
NSString *urlString = @"http:/_post.php";

// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];

[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];

NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];
//[body appendData:[[NSString stringWithFormat:@"%@", post] dataUsingEncoding:NSUTF8StringEncoding]];

// title
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"title\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:uTitle] dataUsingEncoding:NSUTF8StringEncoding]]; // title
// message
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"message\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:uMessage] dataUsingEncoding:NSUTF8StringEncoding]]; // title

/// image

[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"image\"; filename=\"ipodfile.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"action=upload&"] dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[NSData dataWithData:imageData]];

[request setHTTPBody:body];
NSString *msgLength = [NSString stringWithFormat:@"%d", [body length]];
[request addValue: msgLength forHTTPHeaderField:@"Content-Length"];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

[self alert];

sending lattitude and long to server

// assemble the POST data

NSString *post = [NSString stringWithFormat:@"Latitude=%@&Longitude=%@¬e=%@",
[self urlEncodeValue:latitude],
[self urlEncodeValue:longitude],
[self urlEncodeValue:note],
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@""]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

Tuesday, June 22, 2010

post images to server

Monday, June 21, 2010

camera control on iphne

this is the link for camera demo

Thursday, June 17, 2010

Base 64 implementation

i got it form

//// class name Base64.h

@interface Base64 : NSObject {

+ (void) initialize;
+ (NSString*) encode:(const uint8_t*) input length:(NSInteger) length;
+ (NSString*) encode:(NSData*) rawBytes;
+ (NSData*) decode:(const char*) string length:(NSInteger) inputLength;
+ (NSData*) decode:(NSString*) string;


/// class name Base64.m

#import "Base64.h"

@implementation Base64
#define ArrayLength(x) (sizeof(x)/sizeof(*(x)))

static char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static char decodingTable[128];

+ (void) initialize {
if (self == [Base64 class]) {
memset(decodingTable, 0, ArrayLength(decodingTable));
for (NSInteger i = 0; i < ArrayLength(encodingTable); i++) {
decodingTable[encodingTable[i]] = i;

+ (NSString*) encode:(const uint8_t*) input length:(NSInteger) length {
NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t* output = (uint8_t*)data.mutableBytes;

for (NSInteger i = 0; i < length; i += 3) {
NSInteger value = 0;
for (NSInteger j = i; j < (i + 3); j++) {
value <<= 8;

if (j < length) {
value |= (0xFF & input[j]);

NSInteger index = (i / 3) * 4;
output[index + 0] = encodingTable[(value >> 18) & 0x3F];
output[index + 1] = encodingTable[(value >> 12) & 0x3F];
output[index + 2] = (i + 1) < length ? encodingTable[(value >> 6) & 0x3F] : '=';
output[index + 3] = (i + 2) < length ? encodingTable[(value >> 0) & 0x3F] : '=';

return [[[NSString alloc] initWithData:data
encoding:NSASCIIStringEncoding] autorelease];

+ (NSString*) encode:(NSData*) rawBytes {
return [self encode:(const uint8_t*) rawBytes.bytes length:rawBytes.length];

+ (NSData*) decode:(const char*) string length:(NSInteger) inputLength {
if ((string == NULL) || (inputLength % 4 != 0)) {
return nil;

while (inputLength > 0 && string[inputLength - 1] == '=') {

NSInteger outputLength = inputLength * 3 / 4;
NSMutableData* data = [NSMutableData dataWithLength:outputLength];
uint8_t* output = data.mutableBytes;

NSInteger inputPoint = 0;
NSInteger outputPoint = 0;
while (inputPoint < inputLength) {
char i0 = string[inputPoint++];
char i1 = string[inputPoint++];
char i2 = inputPoint < inputLength ? string[inputPoint++] : 'A'; /* 'A' will decode to \0 */
char i3 = inputPoint < inputLength ? string[inputPoint++] : 'A';

output[outputPoint++] = (decodingTable[i0] << 2) | (decodingTable[i1] >> 4);
if (outputPoint < outputLength) {
output[outputPoint++] = ((decodingTable[i1] & 0xf) << 4) | (decodingTable[i2] >> 2);
if (outputPoint < outputLength) {
output[outputPoint++] = ((decodingTable[i2] & 0x3) << 6) | decodingTable[i3];

return data;

+ (NSData*) decode:(NSString*) string {
return [self decode:[string cStringUsingEncoding:NSASCIIStringEncoding] length:string.length];


/// main class import base64.h

and here we go

NSString *post1 =[NSString stringWithFormat:@"%@|%@",tfUsername.text, tfPassword.text];

NSData *data = [post1 dataUsingEncoding: NSASCIIStringEncoding];
NSData *encryptedData = [post1 dataUsingEncoding: NSASCIIStringEncoding];

[Base64 initialize];

NSString *b64EncStr1=[Base64 encode:encryptedData];

NSLog(@"Base 64 encoded = %@",b64EncStr1);


If you want to pull data from xml then use NSScanner :)

NSString *a =serverOutput2;// ur string
NSString *checkForValidity;

NSScanner *scanner = [NSScanner scannerWithString:a];

[scanner scanUpToString:@"" intoString:NULL];// write the word u want to scan in @
[scanner scanString:@"" intoString:NULL];
[scanner scanUpToString:@"
" intoString:&checkForValidity];

Wednesday, May 5, 2010

Back to basics

# @interface declaration is identical to a regular function
# @implementation shows a new keyword: super

* Similar to Java, Objective-C only has one parent class.
* Accessing it's super constructor is done through [super init] and this is required for proper inheritance.
* This returns an instance which you assign to another new keyword, self. Self is similar to this in Java and C++.

# if ( self ) is the same as if ( self != nil ) to make sure that the super constructor successfully returned a new object. nil is Objective-C's form of NULL from C/C++. This is gotten from including NSObject.
# After you've initialized the varialbes, you return yourself with return self;
# The deafult constructor is -(id) init;
# Constructors in Objective-C are technically just "init" methods, they aren't a special construct like they are in C++ and Java.
+ is used. The + denotes a class level function.

Interface is a class which contain all unimplemented methods( can call them also abstract methods)
We will implement these methods in derived class of interface.
ie an interface is actually not inherited but implemented.
We cann't create an instance of interface object instead we can create an instance for derived class objects


classes in Objective-C provide the basic construct for encapsulating some data with the actions that operate on that data. An object is a runtime instance of a class,

Protocols and Delegates

Protocols and Delegates

A protocol declares methods that can be implemented by any class. Protocols are not classes themselves. They simply define an interface that other objects are responsible for implementing. When you implement the methods of a protocol in one of your classes, your class is said to conform to that protocol.

Protocols are used frequently to specify the interface for delegate objects. A delegate object is an object that acts on behalf of, or in coordination with, another object. The best way to look at the interplay between protocols, delegates, and other objects is to look at an example.

The UIApplication class implements the required behavior of an application. Instead of forcing you to subclass UIApplication to receive simple notifications about the current state of the application, the UIApplication class delivers those notifications by calling specific methods of its assigned delegate object. An object that implements the methods of the UIApplicationDelegate protocol can receive those notifications and provide an appropriate response.

The declaration of a protocol looks similar to that of a class interface, with the exceptions that protocols do not have a parent class and they do not define instance variables. The following example shows a simple protocol declaration with one method:

@protocol MyProtocol
- (void)myProtocolMethod;

Thursday, April 22, 2010

In the MVC design pattern, the model layer consists of objects that represent the data your application manages. The objects in this layer should be organized in the way that makes the most sense for the data. External interactions with model objects occur through a well-defined set of interfaces, whose job is to ensure the integrity of the underlying data at all times.

The view layer defines the presentation format and appearance of the application. This layer consists of your application’s windows, views, and controls. The views can be standard system views or custom views you create. You configure these views to display the data from your model objects in an appropriate way. In addition, your view objects need to generate notifications in response to events and user interactions with that data.

The controller layer acts as the bridge between the model and view layers. It receives the notifications generated by the view layer and uses them to make the corresponding changes in the data model. Similarly, if the data in the data layer changes for other reasons (perhaps because of some internal computation loop), it notifies an appropriate controller object, which then updates the views.


View is just a GUI so when user interact with GUI (controller) and modify data indirectly(which is a model)


In the MVC design pattern, the model layer consists of objects that represent the data your application manages. The objects in this layer should be organized in the way that makes the most sense for the data. External interactions with model objects occur through a well-defined set of interfaces, whose job is to ensure the integrity of the underlying data at all times.

The view layer defines the presentation format and appearance of the application. This layer consists of your application’s windows, views, and controls. The views can be standard system views or custom views you create. You configure these views to display the data from your model objects in an appropriate way. In addition, your view objects need to generate notifications in response to events and user interactions with that data.

The controller layer acts as the bridge between the model and view layers. It receives the notifications generated by the view layer and uses them to make the corresponding changes in the data model. Similarly, if the data in the data layer changes for other reasons (perhaps because of some internal computation loop), it notifies an appropriate controller object, which then updates the views.

Wednesday, April 21, 2010

Revolute joint

public var rev1:b2RevoluteJoint;
var bodyDef2:b2BodyDef;
var boxDef2:b2PolygonDef;

bodyDef2 = new b2BodyDef();
bodyDef2.position.Set(26, 12.5);
//bodyDef2.angle = -.5;

boxDef2 = new b2PolygonDef();
boxDef2.SetAsBox(3, .1);//7
boxDef2.friction = .1;
boxDef2.density = 12.1;
body2 = m_world.CreateBody(bodyDef2);

/////////////// body 20

var bodyDef20:b2BodyDef;
var boxDef20:b2PolygonDef;

bodyDef20 = new b2BodyDef();
bodyDef20.position.Set(23, 12.5);
//bodyDef2.angle = -.5;

boxDef20 = new b2PolygonDef();
boxDef20.SetAsBox(.5, .1);//7
boxDef20.friction = .1;
boxDef20.density = 0;
body20 = m_world.CreateBody(bodyDef20);


var rjdDef:b2RevoluteJointDef = new b2RevoluteJointDef();
rjdDef.Initialize(body2, body20, body20.GetWorldCenter() );

// rjdDef.maxMotorTorque=16600.0;

rjdDef. upperAngle=0.25*3.14
rev1 = m_world.CreateJoint(rjdDef) as b2RevoluteJoint;

/////// center is static and other is dynamic .. and you can play with dynamic///
somthing like this


Wednesday, April 14, 2010

cocos2d updates implementation

Thursday, April 8, 2010

Particle effect Implementation

CCParticleSystem *emitter = [CCParticleExplosion node];

emitter = [[CCParticleMeteor alloc] init];
emitter = [[CCParticleFire alloc] init];
emitter.texture = [[CCTextureCache sharedTextureCache] addImage:@"fire.png"];
emitter.position = ccp(location.x,location.y); = 0.2f;
emitter.duration = 0.3f;
emitter.lifeVar = 0.3f;

[self addChild:emitter];

Monday, March 29, 2010

Wednesday, March 10, 2010

Animate sprite

sheet99 = [CCSpriteSheet spriteSheetWithFile:@"fan_l1l2_left.png" capacity:12];
[self addChild:sheet99 z:4 tag:kTagSpriteSheet];
sprite99 = [sheet99 createSpriteWithRect:CGRectMake(0,0,300,400)];//32 * idx,32 * idy,32,32
[sheet99 addChild:sprite99 z:7];

CCAnimation *animation = [CCAnimation animationWithName:@"dance" delay:.1f ];

[animation addFrameWithTexture:sheet99.texture rect:CGRectMake(-121,0,242,400)];//-121
[animation addFrameWithTexture:sheet99.texture rect:CGRectMake(0, 0, 242,400)];//0,0
id action = [CCAnimate actionWithAnimation:animation];
// Run the animation
//id repeatAction = [CCRepeat actionWithAction:action times:100];

// To repeat forever, use this
id repeatAction = [CCRepeatForever actionWithAction:action];

[sprite99 runAction:repeatAction];

body and updation

b2BodyDef bodyDef9c8;
bodyDef9c8.type =b2_staticBody;

//bodyDef.userData = sprite;
b2Body* body9c8;
//= world->CreateBody(&groundBodyDef5);
body9c8 = world->CreateBody(&bodyDef9c8);

// Define another box shape for our dynamic body.
b2PolygonShape dynamicBox9c8;
dynamicBox9c8.SetAsBox(1.7f, .1f);//These are mid points for our 1m box

// Define the dynamic body fixture.
b2FixtureDef fixture9c8;
//fixture99.userData = @"Box";

fixture9c8.shape = &dynamicBox9c8;
fixture9c8.density = 0;
fixture9c8.friction = 0.3f;

body0->SetTransform (b2Vec2(8,12),0);//target replaced by setXform

Friday, February 19, 2010

Tuesday, February 9, 2010

stack in objc

for (float32 x =0.0f; x<300.0f; x=x+1.0f) {
float32 y=1.0f;
// Define the static body.
//Set up a 1m squared box in the physics world
b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;

bodyDef.position.Set(x, y);
b2Body *body = world->CreateBody(&bodyDef);

// Define another box shape for our static body.
b2PolygonShape staticBox;
staticBox.SetAsBox(.5f, .5f);//These are mid points for our 1m box

// Define the static body fixture.
b2FixtureDef fixtureDef;
fixtureDef.shape = &staticBox;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;

Thursday, January 7, 2010

create body IPhone

// body
b2BodyDef groundBodyDef2;
groundBodyDef2.position.Set(8, 9);
b2Body* groundBody2 = world->CreateBody(&groundBodyDef2);
b2PolygonShape groundBox2;
groundBox2.SetAsBox(1.5f, .1f);//SetAsEdge(b2Vec2(3,3), b2Vec2(3,0));

// triangle
b2BodyDef polyBodyDef; // Define the body
polyBodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
b2Body *poly = world->CreateBody(&polyBodyDef);

b2PolygonShape polyShapeDef; // Define the shape
//polyShapeDef.SetAsBox(1.0f, 1.0f);
polyShapeDef.m_vertexCount = 3;
polyShapeDef.m_vertices[0].Set(-1, 0);
polyShapeDef.m_vertices[1].Set(1, 0);
polyShapeDef.m_vertices[2].Set(0, 1.5);

b2FixtureDef polyFixtureDef; // Define the fixture
polyFixtureDef.shape = &polyShapeDef;
polyFixtureDef.density = 1.0f;
polyFixtureDef.friction = 0.3f;