Saturday 21 July 2012

JSON Using Local File Implementation in Xcode

Step1: Create A Xcode project in Name of Json

Step2: JSON Files Download Link : http://www.mediafire.com/?iw9p1bap515cojn

Step3: Import the Downloaded file into your Project.

Step4: Create the json file in Name of Asan.json.

Step5: Asan.json Write a Below Coding and Save File.

{
    "Details":
    [
        {
            "Name": "Asan",
            "Native": "From TVL"
        },
        {
            "Name": "Elavarasan",
            "Native": "From Ariyalur"
        },
        {
            "Name": "Santhosh",
            "Native": "From Vellore"
        }
    ]
}


Step6: Asan.json file is implemented to project.

Step7: open .h File and import the Codings

#import <UIKit/UIKit.h>

@interface RootViewController : UITableViewController {

    NSArray *tableData;
}

@property (nonatomic, retain) NSArray *tableData;

@end


Step8: open .m File and import the Codings

#import "JSON.h"

@synthesize tableData;

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // Download JSON
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Asan" ofType:@"json"]; 
    NSString *fileContent = [[NSString alloc] initWithContentsOfFile:filePath];
    
    // Create parser
    SBJSON *parser = [[SBJSON alloc] init];
    NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil];
[parser release], parser = nil;
    
    // Set tableData
    [self setTableData:[data objectForKey:@"Details"]];
    
}


// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [tableData 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) {
        // Change UITableViewCellStyle
        cell = [[[UITableViewCell alloc
                 initWithStyle:UITableViewCellStyleSubtitle 
                 reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Get item from tableData
    NSDictionary *item = [tableData objectAtIndex:[indexPath row]];
    // Set text on textLabel
    [[cell textLabel] setText:[item objectForKey:@"Name"]];
    // Set text on detailTextLabel
    [[cell detailTextLabel] setText:[item objectForKey:@"Native"]];
    
    return cell;
}


- (void)viewDidUnload
{
    [self setTableData:nil];
    [super viewDidUnload];
}

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


Step9: Build and Run the Xcode Application





JSON using for Web Service in Xcode

Sample Project Download Link :  http://www.mediafire.com/?yqeydj9lv10l97u 

JSON Files Download Link : http://www.mediafire.com/?iw9p1bap515cojn


JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
In this tutorial you would learn to load, parse and show JSON!

Start Xcode and create a new project based on the 'Navigation-based Application' template.
create-project.png
Give it a name and choose 'iPhone' as the 'Device Family'. Create a new group into your project folder and call it 'JSON'.
Download de compressed 'JSON' folder from the attachments. Uncompress the downloaded .zip file and drag the files in the JSON group, inside your project folder. Set the option 'Copy items into destination group's folder (if needed)' checked. Click on 'Finish'.
add-json.png
And now it's time to write code.


Open the RootViewController.h, and change the code like below. Add an NSDictionary to hold the tabledata.
// RootViewController.h
#import <UIKit/UIKit.h> 
@interface RootViewController : UITableViewController 
{
 NSArray *tableData;
} 
@property (nonatomic, retain) NSArray *tableData;
 @end


Open the RootViewController.m, and change the code like below. First import the "JSON.h" and synthesize the NSDictionary. Then download the JSON and write his contents in your TableViewcontroller.


// Add this line on top of your RootViewController.m
#import "JSON.h" 

// And directly under the @implementation RootviewController add the following line
@synthesize tableData;

When the view will appear we will download the JSON. Change the method viewWillAppear as below.

- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];


// Download JSON
NSString *jsonString = [NSString stringWithContentsOfURL stringWithContentsOfURL:[NSURL URLWithString:@"http://altinkonline.nl/temp/xcode-and-parsing-json.json"] encoding
encoding:NSStringEncodingConversionAllowLossy error error:nil];


// Create parser 
 SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *results = [parser objectWithString:jsonString error:nil];
[parser release], parser = nil;


// Set tableData
[self setTableData:[results objectForKey:@"items"]];
}


Now we have the parsed JSON we will show the JSON on the UITableView. Change the functions in your "RootViewController.m" as below.


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of items in tabledata
return [tableData 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) 
{
// Change UITableViewCellStyle 
 cell = [[[UITableViewCell alloc] initWithStyle initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier reuseIdentifier:CellIdentifier] autorelease];
} 

// Get item from tableData
NSDictionary *item = [tableData objectAtIndex:[indexPath row]];


// Set text on textLabel
[[cell textLabel] setText:[item objectForKey:@"title"]];


// Set text on detailTextLabel
[[cell detailTextLabel] setText:[item objectForKey:@"description"]]
 return cell;
}

// When view is unloaded we don't need the tableData because we reload them in the ViewWillAppear- (void)viewDidUnload
{
[self setTableData:nil];
[super viewDidUnload];
}

// Release tableData on exit

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

Thursday 19 July 2012

URL implementation User Registration Form in Xcode

.h File

#import <UIKit/UIKit.h>

@interface RootViewController : UIViewController
{
    IBOutlet UIActivityIndicatorView *activityView;
    IBOutlet UILabel *lbl_device;
    NSString *content;
}

-(void)updateCounter:(NSTimer *)theTimer;
-(void)countdownTimer;

@property(nonatomic,retain)  UIActivityIndicatorView *activityView;

@end



.m File

#import "RootViewController.h"
#import "screen2.h"
#import "profile.h"

@implementation RootViewController
@synthesize activityView;

NSTimer *timer;
int hours, minutes, seconds;
int secondsLeft;


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBarHidden=YES;
    secondsLeft = 5;
    [self countdownTimer];
}

- (void)updateCounter:(NSTimer *)theTimer
{
    if(secondsLeft > 0 )
    {
        secondsLeft-- ;
        hours = secondsLeft / 3600;
        minutes = (secondsLeft % 3600) / 60;
        seconds = (secondsLeft %3600) % 60;
       // myCounterLabel.text = [NSString stringWithFormat:@":%02d",seconds];
     
        if (secondsLeft==0)
        {
         
            UIDevice *myDevice = [UIDevice currentDevice];
            NSString *deviceUDID = [myDevice uniqueIdentifier];
            NSLog(@"%@",deviceUDID);
            lbl_device.text=deviceUDID;
            self.navigationController.navigationBarHidden=YES;
         
            NSString *stringURL =[NSString stringWithFormat: @"http://www.support.iwedplanner.com/KnowledgeBowl/KnowBowl_Login.aspx?UD_ID=%@",deviceUDID,nil];
            NSLog(stringURL);
            NSURL *url = [NSURL URLWithString:stringURL];
            content=[NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:NULL];
            NSLog(content);
            NSString* result = content;
            NSArray* components = [result componentsSeparatedByString:@"/n"];
         
         
            NSString* name1 = [components objectAtIndex:1];
            NSString* udid1 = [components objectAtIndex:2];
            NSLog(@"name is %@",name1);
            NSLog(@"device id is %@",udid1);
                       if([udid1 isEqualToString:@"UD_IDExist"])
             
            {
             // Check challenge availability
             
                NSString *stringURL =[NSString stringWithFormat: @"http://www.support.iwedplanner.com/KnowledgeBowl/KnowBowl_UserAvailability.aspx?UserName2=%@",name1,nil];
                NSLog(stringURL);
                NSURL *url = [NSURL URLWithString:stringURL];
                //NSLog(url);
                content=[NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:NULL];
                if ([content isEqualToString:@"|UserName2 Not Availblity|"])
                {
                    screen2 *main=[[screen2 alloc]init];
                   [self.navigationController pushViewController:main animated:YES];
                }
                else
                {
                    User2Response *u2_play=[[User2Response alloc]init];
                    [self.navigationController pushViewController:u2_play animated:YES];
                }              
            }
            else
            {
                profile *prof1=[[profile alloc]init];
                [self.navigationController pushViewController:prof1 animated:YES];
            }
         

        }
    }
 
}


-(void)countdownTimer
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];
    [pool release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end

Send Email and SMS in Xcode

Step1 : Add the framework into your project: MessageUI.framework


.h File

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

@interface MessageViewController : UIViewController <MFMailComposeViewControllerDelegate, MFMessageComposeViewControllerDelegate>

{

}

- (IBAction)btnEmail_Clicked:(id)sender;
- (IBAction)btnMessage_Clicked:(id)sender;
- (IBAction)btnCall_Clicked:(id)sender;

@end


.m File

#import "MessageViewController.h"


@implementation MessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];

self.title = @"Message sending";
}

- (IBAction)btnEmail_Clicked:(id)sender
{
     if ([MFMailComposeViewController canSendMail])
    {

         MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setToRecipients:[NSArray arrayWithObject:@"user@gmail.com"]];
[controller setSubject:@"iPhone Email Example Mail"];
[controller setMessageBody:@"http://iphoneapp-dev.blogspot.com" isHTML:NO];
[self presentModalViewController:controller animated:YES];
[controller release];
}
else
{ 
UIAlertView* alert=[[UIAlertView alloc]initWithTitle:@"No Mail Accounts" message:@"Please set up a Mail account in order to send email." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
}
}

- (IBAction)btnMessage_Clicked:(id)sender
{
MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
if([MFMessageComposeViewController canSendText])
{
controller.body = @"Hello Friends this is sample text message.";
controller.recipients = [NSArray arrayWithObjects:@"+919999999999", nil];
controller.messageComposeDelegate = self;
[self presentModalViewController:controller animated:YES];
}
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {

switch (result) {
case MessageComposeResultCancelled:
NSLog(@"Cancelled");
break;
case MessageComposeResultFailed:
NSLog(@"Failed");
break;
case MessageComposeResultSent:
NSLog(@"Send");
break;
default:
break;
}

[self dismissModalViewControllerAnimated:YES];
}

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

if (result == MFMailComposeResultSent) {
NSLog(@"It's away!");
}
[self dismissModalViewControllerAnimated:YES];
}

- (IBAction)btnCall_Clicked:(id)sender
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"+919999999999"]];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
 
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


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


@end


URL Using Login Application in XCode

.h File

@interface login : UIViewController
{
    NSString *content;
}
-(IBAction)log:(id)sender;
-(IBAction)signup:(id)sender;
@property (retain, nonatomic) IBOutlet UITextField *UserName;
@property (retain, nonatomic) IBOutlet UITextField *Password;
@end


.m File

#import "screen2.h"
#import "Reachability.h"

@implementation login

@synthesize UserName,Password;
-(IBAction)log:(id)sender
{
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.google.com"];
NetworkStatus internetStatus = [reach currentReachabilityStatus];

if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
       {
/// Create an alert if connection doesn't work
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:@"No Internet Connection"   message:@""
delegate:self
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[myAlert show];
[myAlert release];
}

 
    NSString *stringURL =[NSString stringWithFormat: @"http://www.support.iwedplanner.com/KnowledgeBowl/KnowBowl_User.aspx?UserName=%@&Password=%@",UserName.text,Password.text,nil];
    NSURL *url = [NSURL URLWithString:stringURL];
    content=[NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:NULL];
    if([content hasPrefix:@"|Invalid UserName/Password |"])
     
    {
        UIAlertView *objAlert = [[UIAlertView alloc] initWithTitle:@"Message!" message:@"Invalid UserName/Password" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
        [objAlert setTag:1];
        [objAlert show];
        [objAlert release];
        UserName.text=@"";
        Password.text=@"";
    }
    else
    {
        screen2 *start=[[screen2 alloc]init];
        [self.navigationController pushViewController:start animated:YES];
    }

}



Wednesday 18 July 2012

UIAlertView and UIActionSheet in XCode


.h File

@interface ViewController : UIViewController <UIAlertViewDelegate> 
{
}
@end       


.m File:
UIAlertView *alert=[[UIAlertView alloc]
                            initWithTitle:@"Hello World!"
                            message:@"This is your first UIAlertview message"
                            delegate:self
                            cancelButtonTitle:@"OK"
                            otherButtonTitles:nil];        //otherButtonTitles:@”Next Page”,@”Last Page”];
[alert addButtonWithTitle:@"Next Page"];
  [alert addButtonWithTitle:@"Last Page"];

       [alert show];
        [alert release];
   


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex 
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:@"OK"])
{
NSLog(@"Next Page was selected.");
[self dismissModalViewControllerAnimated:YES];
}

        else if([title isEqualToString:@"Next Page"])
{
//Codings
NSLog(@"Next Page was selected.");
}

else if([title isEqualToString:@"Next Page"])
{
//Codings
NSLog(@"Last Page was selected.");
}
}



     UIActionSheet

.h File:
@interface ViewController : UIViewController <UIActionSheetDelegate>
{
  UIActionSheet *sheet;
}
@end
.m File:
 UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Share" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Facebook", @"Twitter", nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
    [actionSheet showInView:self.view];
    [actionSheet release];


-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex 
{
    if(buttonIndex == 0) 
   {
        //An Action 
   } 
   else if(buttonIndex == 1) 
  {
        //Another Action
  }
}


Orientation in Xcode

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
 
     if((self.interfaceOrientation == UIDeviceOrientationLandscapeLeft) || (self.interfaceOrientation == UIDeviceOrientationLandscapeRight))
    {
        [Lable1 setFrame:CGRectMake(131, 31, 218, 30)];
        [Lable2 setFrame:CGRectMake(131, 82, 218, 30)];
     
        button1.frame = CGRectMake(173, 161, 110, 43);
     
[imgview setFrame:CGRectMake(0,225,488,46)];
    }
else if((self.interfaceOrientation == UIDeviceOrientationPortrait) || (self.interfaceOrientation == UIDeviceOrientationPortraitUpsideDown))
    {
        [Lable1 setFrame:CGRectMake(131, 31, 218, 30)];
        [Lable2 setFrame:CGRectMake(131, 82, 218, 30)];
     
        button1.frame = CGRectMake(173, 161, 110, 43);
     
[imgview setFrame:CGRectMake(0,225,488,46)];
    }
}

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
 if((self.interfaceOrientation == UIDeviceOrientationLandscapeLeft) || (self.interfaceOrientation == UIDeviceOrientationLandscapeRight))
    {
        [Lable1 setFrame:CGRectMake(131, 31, 218, 30)];
        [Lable2 setFrame:CGRectMake(131, 82, 218, 30)];
     
        button1.frame = CGRectMake(173, 161, 110, 43);
     
[imgview setFrame:CGRectMake(0,225,488,46)];
    }
else if((self.interfaceOrientation == UIDeviceOrientationPortrait) || (self.interfaceOrientation == UIDeviceOrientationPortraitUpsideDown))
    {
        [Lable1 setFrame:CGRectMake(131, 31, 218, 30)];
        [Lable2 setFrame:CGRectMake(131, 82, 218, 30)];
     
        button1.frame = CGRectMake(173, 161, 110, 43);
     
[imgview setFrame:CGRectMake(0,225,488,46)];
    }
}



Another Method:


Step1: Create 2 Views in Single Xib Page.

Step2: One is Portrait format
           Another is landscape format

Step3: Add the coding into .h File


@property (nonatomic, retain) IBOutlet UIView *portraitView;
@property (nonatomic, retain) IBOutlet UIView *landscapeView;

Step4: Connect the outlets   Portrait--> portraitView  & landscape -->  landscapeView.

Step5: Add the coding into .m File

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if((self.interfaceOrientation == UIDeviceOrientationLandscapeLeft) || (self.interfaceOrientation == UIDeviceOrientationLandscapeRight))
    {
        self.view = self.landscapeView;
    }
else if((self.interfaceOrientation == UIDeviceOrientationPortrait) || (self.interfaceOrientation == UIDeviceOrientationPortraitUpsideDown))
    {
        self.view = self.portraitView;
    }
}

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
if((self.interfaceOrientation == UIDeviceOrientationLandscapeLeft) || (self.interfaceOrientation == UIDeviceOrientationLandscapeRight))
    {
        self.view = self.landscapeView;
    }
    else if((self.interfaceOrientation == UIDeviceOrientationPortrait) || (self.interfaceOrientation == UIDeviceOrientationPortraitUpsideDown))
    {
        self.view = self.portraitView;
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

Login Coding in iOS

-(IBAction)login:(id)sender
{
    NSString *user=username.text;
    NSString *pass=password.text;
    NSString *name=@"asan";
    NSString *word=@"111";
    
    if ([user isEqual:name]&&[pass isEqual:word]) 
    {
       /* Sentient *som=[[Sentient alloc]init];
        [self.navigationController pushViewController:som animated:YES];*/
        
    }
   else
   {
       UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"LoginFailed" 
       message:@"password Mismatch" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles: nil];
       [alert show];
       [alert release];
   }
}

Hides a Keyboard in iOS

Text Field Should Return:


.h File



@interface ViewController : UIViewController<UITextFieldDelegate>
{
}
@property (retain, nonatomic) IBOutlet UITextField *userTxtfld;
@property (retain, nonatomic) IBOutlet UITextField *passTxtfld;
@end

.m File
@synthesize selecteddate
- (void)viewDidLoad
{
    [super viewDidLoad];
    userTxtfld.delegate=self;
    passTxtfld.delegate=self;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == userTxtfld)
    {
        [textField resignFirstResponder];
    }
    else if (textField == passTxtfld)
    {
        [textField resignFirstResponder];
    }
    return textField;
}


Textview Should Return:

.h File :
@interface ViewController : UIViewController
{
}
@property (retain, nonatomic) IBOutlet UITextView *textview;

.m File
@synthesize  textview;
- (void)viewDidLoad
{
    [super viewDidLoad];
    textview.delegate=self;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    if([text isEqualToString:@"\n"]) 
   {
        [textview resignFirstResponder];
        return NO;
    }
    return YES;
}

BackGround Touched Hides the Keyboard:


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [Name resignFirstResponder];
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{   
    [Name resignFirstResponder];
}

SQLITE using iOS

Database(Automatically Create a Database)

dbacc.h
#import <UIKit/UIKit.h>
#import <sqlite3.h>


@interface dbacc : UIViewController
{
sqlite3 *contactDB;
    NSString *databasePath;
    NSString *transfer_name;
    NSString *transfer_amount;
    
}
@property(nonatomic,retain)NSString *transfer_name;
@property(nonatomic,retain)NSString *transfer_amount;

- (IBAction) saveData;
- (NSMutableArray*)getdata;
- (IBAction)deletedata;
@end





dbacc.m
#import "dbacc.h"

@implementation dbacc
@synthesize transfer_name,transfer_amount;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void) saveData
{
   sqlite3_stmt    *statement;
    const char *dbpath = [databasePath UTF8String];
    
    if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
    {
        NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO account (name,amount) VALUES (\"%@\",\"%@\")", transfer_name,transfer_amount];
        const char *insert_stmt = [insertSQL UTF8String];
        sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
        if (sqlite3_step(statement) == SQLITE_DONE)
        {
            NSLog(@"inserted");
        } 
        else 
        {
            NSLog(@"failed");
        }

        sqlite3_finalize(statement);
        sqlite3_close(contactDB);
        
    }
}

- (NSMutableArray*)getdata
{
    NSString *docsdir;
    NSArray *dirpaths;
    
    dirpaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsdir=[dirpaths objectAtIndex:0];
    databasePath = [[NSString alloc] initWithString: [docsdir stringByAppendingPathComponent
                                                      @"christmas.db"]];
    const char *dbpath = [databasePath UTF8String];
        
    if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
    {
        NSMutableArray *products = [[[NSMutableArray alloc] init] autorelease];
        
        char const *sql="select * from favour";
       
        sqlite3_stmt *statement;
        int sqlResult = sqlite3_prepare_v2(contactDB, sql, -1, & statement, NULL);
        if ( sqlResult== SQLITE_OK
        {
            // Step through the results - once for each row.
            while (sqlite3_step(statement) == SQLITE_ROW
            {
                
                //fan1 *pdt=[[fan1 alloc]init];
                char *name = (char *)sqlite3_column_text(statement, 1);
                char *amount = (char *)sqlite3_column_text(statement, 2);
                //pdt.name = (name) ? [NSString stringWithUTF8String:name] :@"";
              // pdt.image = (image) ? [NSString stringWithUTF8String:image] :@"";
                
                [products addObject:pdt];
                [pdt release];
            }
            sqlite3_finalize(statement);
        }
        
        else {
            NSLog(@"Problem with the database:");
            NSLog(@"%d",sqlResult);
        }
        return products;

    }
    
}

- (IBAction)deletedata
{
    NSString *docsdir;
    NSArray *dirpaths;
    
    dirpaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsdir=[dirpaths objectAtIndex:0];
    databasePath = [[NSString alloc] initWithString: [docsdir stringByAppendingPathComponent
                                                      @"christmas.db"]];
    const char *dbpath = [databasePath UTF8String];
     sqlite3_stmt *statement;
    if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
    {
       
        NSString *deleteSQL = [NSString stringWithFormat:@"DELETE FROM account WHERE name='%@'",transfer_delete];
        const char *delete_stmt = [deleteSQL UTF8String];
        sqlite3_prepare_v2(contactDB, delete_stmt, -1, &statement, NULL);
    }
    if (sqlite3_step(statement) == SQLITE_DONE)
    {
        NSLog(@"inserted");
    } 
    else 
    {
        NSLog(@"failed");
    }
    
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    NSString *docsdir;
    NSArray *dirpaths;
    
    dirpaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsdir=[dirpaths objectAtIndex:0];
    databasePath = [[NSString alloc] initWithString: [docsdir stringByAppendingPathComponent
                                     @"bank.db"]];
    
    // NSFileManager *filemgr = [NSFileManager defaultManager];
    
    //  if ([filemgr fileExistsAtPath: databasePath ] == NO)
    //  {
    const char *dbpath = [databasePath UTF8String];
    
    if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
    {
        char *errMsg;
        const char *sql_stmt = "CREATE TABLE IF NOT EXISTS account (NAME TEXT,AMOUNT TEXT)";
        
        if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
        {
            //status.text = @"Failed to create table";
            NSLog(@"Failed to create table");
        }
        
        sqlite3_close(contactDB);
        
    } else {
        //status.text = @"Failed to open/create database";
        NSLog(@"Failed to open/create database");

    }

    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

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

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end



Credit.h
@interface Credit : UIViewController
{
    IBOutlet UITextField *name;
    IBOutlet UITextField *amount;
}
-(IBAction)Credit:(id)sender;
@end


Credit.m
-(IBAction)Credit:(id)sender
{
    dbacc *db=[[dbacc alloc]init];
    db.transfer_name=name.text;
    db.transfer_amount=amount.text;
    [db viewDidLoad];
    [db saveData];
    [db getdata];
    [db deletedata];
    [db release];
}



Credit.xib
         1.map the values to be name,amount,saveData,getdata,deletedata.
         2.Add the two frameworks are  libsqlite3.0.dylib,libsqlite3.dylib

CountDownTimer for iOS

.h File

@interface ViewController : UIViewController
{
    IBOutlet UILabel *myCounterLabel;
 
}

-(void)updateCounter:(NSTimer *)theTimer;
-(void)countdownTimer;
@property (nonatomic, retain) UILabel *myCounterLabel;


.m File


NSTimer *timer;
int hours, minutes, seconds;
int secondsLeft;




secondsLeft = 10;
 
    [self countdownTimer];




- (void)updateCounter:(NSTimer *)theTimer {
    if(secondsLeft > 0 ){
        secondsLeft -- ;
        hours = secondsLeft / 3600;
        minutes = (secondsLeft % 3600) / 60;
        seconds = (secondsLeft %3600) % 60;
        myCounterLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours,minutes,seconds];
        if (secondsLeft==0)
        {
            /*screen2 *np=[[screen2 alloc]init];
            [self.navigationController pushViewController:np animated:YES];*/
        }
    }
}


-(void)countdownTimer
{
 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];
    [pool release];
}


- (void)viewWillDisappear:(BOOL)animated
{
    [timer invalidate];
    timer = nil;
}


Bar Button Item in iOS

.h File

-(void)addtofavorites;


.m File

-(void)ViewDidLoad
{
UIBarButtonItem *add=[[UIBarButtonItem alloc]initWithTitle:@"Add To Favorites" style:UIBarButtonSystemItemFlexibleSpace target:self action:@selector(addtofavorites)];                          self.navigationItem.rightBarButtonItem=add;
}


-(void)addtofavorites
{
          //NavigationCodings
}


Create Google Analytics in iOS

 You can write the following code in didFinishLaunchingWithOptions in app delegate.

[[GANTracker sharedTracker] startTrackerWithAccountID:@xxxxxxxxxx-yyyyyyyy-zzzzz" dispatchPeriod:kGANDispatchPeriodSec delegate:nil];
NSError *error;
    if (![[GANTracker sharedTracker] trackPageview:@"/app_launched"withError:&error]) 
{
        // Handle error here
}

In Google Analytics Page:
xxxxxxxxxx-yyyyyyyy-zzzzz--->for getting this number, you can create account in google analytics  and type the project name and get this tracker id number


InProject:
You have to add  cfnetwork framework and add GANTracker header file. and libgoogle analytic.

example: #import<GANTracker.h>

a  from http://code.google.com/apis/analytics/docs/mobile/ios.html



GANTracker for Google Analytics:
1.Download the GANTracker.h File and import the Project.
2.Import the coding into which page has been tracked.

GANTracker.h 

//  GANTracker.h
//  Google Analytics iOS SDK
//  Version: 1.4
//  Copyright 2009 Google Inc. All rights reserved.

extern NSString* const kGANTrackerErrorDomain;

typedef enum {
  
  kGANTrackerInvalidInputError = 0xbade7a9,
  kGANTrackerEventsPerSessionLimitError = 0xbad5704e,
  kGANTrackerNotStartedError = 0xbada55,
  kGANTrackerDatabaseError = 0xbadbaddb
GANErrorCode;

#define kGANMaxCustomVariables 5
#define kGANMaxCustomVariableLength 64

typedef enum {
  kGANVisitorScope = 1U,
  kGANSessionScope = 2U,
  kGANPageScope = 3U
} GANCVScope;

@protocol GANTrackerDelegate;
typedef struct __GANTrackerPrivate GANTrackerPrivate;

// Google Analytics tracker interface. Tracked pageviews and events are stored
// in a persistent store and dispatched in the background to the server.

@interface GANTracker : NSObject {
 @private
  GANTrackerPrivate *private_;
  BOOL debug_;
  BOOL dryRun_;
  BOOL anonymizeIp_;
  NSUInteger sampleRate_;
}

// If the debug flag is set, debug messages will be written to the log.
// It is useful for debugging calls to the Google Analytics SDK.
// By default, the debug flag is disabled.
@property(readwrite) BOOL debug;

// If the dryRun flag is set, hits will not be sent to Google Analytics.
// It is useful for testing and debugging calls to the Google Analytics SDK.
// By default, the dryRun flag is disabled.
@property(readwrite) BOOL dryRun;

// If the anonymizeIp flag is set, the SDK will anonymize information sent to
// Google Analytics by setting the last octet of the IP address to zero prior
// to its storage and/or submission.
// By default, the anonymizeIp flag is disabled.
@property(readwrite) BOOL anonymizeIp;

// The sampleRate parameter controls the probability that the visitor will be
// sampled. When a visitor is not sampled, no data is submitted to Google
// Analytics about that visitor's activity. If your application is subject to
// heavy traffic spikes, you may wish to adjust the sample rate to ensure
// uninterrupted report tracking. Sampling in Google Analytics occurs
// consistently across unique visitors, ensuring integrity in trending and
// reporting even when sampling is enabled, because unique visitors remain
// included or excluded from the sample, as set from the initiation of
// sampling.
//
// By default, sampleRate is 100, which signifies no sampling. sampleRate may
// be set to any integer value between 0 and 100, inclusive. A value of 90
// requests 90% of visitors to be sampled (10% of visitors to be sampled out).
@property(readwrite) NSUInteger sampleRate;

// Singleton instance of this class for convenience.
+ (GANTracker *)sharedTracker;

// Start the tracker with the specified Google Analytics account ID (the string
// that begins with "UA-") and desired automatic dispatch period (in seconds).
// The dispatcher will dispatch events, if any, every |dispatchPeriod| seconds.
// If a non-positive (e.g. 0 or -1) dispatch period is given, automatic
// dispatch will not be enabled, and the application will need to dispatch
// events manually. An optional delegate may be supplied.
- (void)startTrackerWithAccountID:(NSString *)accountID
                   dispatchPeriod:(NSInteger)dispatchPeriod
                         delegate:(id<GANTrackerDelegate>)delegate;

// Stop the tracker.
- (void)stopTracker;

// Track a page view. Returns YES on success or NO on error (with |error|
// set to the specific error, or nil). You may pass NULL for |error| if you
// don't care about the error.  Note that trackPageview will prepend a '/'
// character if pageURL doesn't start with one.
- (BOOL)trackPageview:(NSString *)pageURL
            withError:(NSError **)error;

// Track an event. The category and action are required. The label and
// value are optional (specify nil for no label and -1 or any negative integer
// for no value). Returns YES on success or NO on error (with |error|
// set to the specific error, or nil). You may pass NULL for |error| if you
// don't care about the error.
- (BOOL)trackEvent:(NSString *)category
            action:(NSString *)action
             label:(NSString *)label
             value:(NSInteger)value
         withError:(NSError **)error;

// Set a custom variable. visitor and session scoped custom variables are stored
// for later use.  Session and page scoped custom variables are attached to each
// event.  Visitor scoped custom variables are sent only on the first event for
// a session. Returns YES on success or NO on error (with |error|
// set to the specific error, or nil). You may pass NULL for |error| if you
// don't care about the error.
- (BOOL)setCustomVariableAtIndex:(NSUInteger)index
                            name:(NSString *)name
                           value:(NSString *)value
                           scope:(GANCVScope)scope
                       withError:(NSError **)error;

// Set a page scoped custom variable.  The variable set is returned with the
// next event only.  It will overwrite any existing visitor or session scoped
// custom variables. Returns YES on success or NO on error (with |error|
// set to the specific error, or nil). You may pass NULL for |error| if you
// don't care about the error.
- (BOOL)setCustomVariableAtIndex:(NSUInteger)index
                            name:(NSString *)name
                           value:(NSString *)value
                       withError:(NSError **)error;

// Returns the value of the custom variable at the index requested.  Returns
// nil if no variable is found or index is out of range.
- (NSString *)getVisitorCustomVarAtIndex:(NSUInteger)index;

// Add a transaction to the Ecommerce buffer.  If a transaction with an orderId
// of orderID is already present, it will be replaced by a new one. All
// transactions and all the items in the buffer will be queued for dispatch once
// trackTransactions is called.  Returns YES on success or NO on error
// (with |error| set to the specific error, or nil). You may pass NULL for
// |error| if you don't care about the error.
- (BOOL)addTransaction:(NSString *)orderID
            totalPrice:(double)totalPrice
             storeName:(NSString *)storeName
              totalTax:(double)totalTax
          shippingCost:(double)shippingCost
             withError:(NSError **)error;

// Add an item to the Ecommerce buffer for the transaction whose orderId matches
// the input parameter orderID.  If no transaction exists, one will be created.
// If an item with the same itemSKU exists, it will be replaced with a new item.
// All the transactions and items in the Ecommerce buffer will be queued for
// dispatch once trackTransactions is called.  Returns YES on success or NO on
// error (with |error| set to the specific error, or nil). You may pass NULL
// for |error| if you don'tcare about the error.
- (BOOL)addItem:(NSString *)orderID
        itemSKU:(NSString *)itemSKU
      itemPrice:(double)itemPrice
      itemCount:(double)itemCount
       itemName:(NSString *)itemName
   itemCategory:(NSString *)itemCategory
      withError:(NSError **)error;

// Tracks all the Ecommerce hits pending in the Ecommerce buffer.
// Returns YES on success or NO on error (with |error|
// set to the specific error, or nil). You may pass NULL for |error| if you
// don't care about the error.
- (BOOL)trackTransactions:(NSError **)error;

// Clears out the buffer of pending Ecommerce hits without sending them.
// Returns YES on success or NO on error (with |error|
// set to the specific error, or nil). You may pass NULL for |error| if you
// don't care about the error.
- (BOOL)clearTransactions:(NSError **)error;

// Sets the campaign to the input parameter referrer. All hits going forward
// will have this campaign attached.  Note that calling setReferrer will trigger
// a new session.
- (BOOL)setReferrer:(NSString *)referrer withError:(NSError **)error;

// Manually dispatch pageviews/events to the server. Returns YES if
// a new dispatch starts.
- (BOOL)dispatch;

// Manually dispatch pageviews/events to the server synchronously until timeout
// time has elapsed.  Returns YES upon completion if there were hits to send and
// all hits were sent successfully. Call this method with care as it will block
// all GANTracker activity until it is done.
- (BOOL)dispatchSynchronous:(NSTimeInterval)timeout;

@end

@protocol GANTrackerDelegate <NSObject>

// Invoked when a hit has been dispatched.
- (void)hitDispatched:(NSString *)hitString;

// Invoked when a dispatch completes. Reports the number of hits
// dispatched and the number of hits that failed to dispatch. Failed
// hits will be retried on next dispatch.
- (void)trackerDispatchDidComplete:(GANTracker *)tracker
                  eventsDispatched:(NSUInteger)hitsDispatched
              eventsFailedDispatch:(NSUInteger)hitsFailedDispatch;

@end