RSS

Category Archives: iphone

iPhone Push Notifications PHP Server

iPhone Push Notifications PHP Server

<?php
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', YOUR_.PEM_FILE);
stream_context_set_option($ctx, 'ssl', 'passphrase', YOUR_PASSPHRASE);

$fp = stream_socket_client(
        'ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);

if (!$fp) {
    exit("Failed to connect: $err $errstr<BR><BR>");
}

echo 'Connected to APN<BR>';


// Create the payload body
$body['aps'] = array(
    'badge' => +1,
    'alert' => 'Testing push notifications',
    'sound' => 'new_wall_paper.wav',
    'action-loc-key' => 'OK'
);

$payload = json_encode($body);

for ($i = 0; $i < count($tokens); $i++) {
    $msg = chr(0) . pack('n', 32) . pack('H*', $tokens [$i]) . pack('n', strlen($payload)) . $payload;
    fwrite($fp, $msg, strlen($msg));
}

echo "Completed sending messages";
fclose($fp);

Advertisements
 
1 Comment

Posted by on July 25, 2014 in iphone, PHP

 

Tags:

How to Display Current Date in your program

Find it difficult to get the current date and time? Then read on, I this tutorial I demonstrate getting current date and time in different programming languages.

Java

Using Calendar

output: 28/6/2012

  Calendar cal = new GregorianCalendar();
  int month = cal.get(Calendar.MONTH);
  int year = cal.get(Calendar.YEAR);
  int day = cal.get(Calendar.DAY_OF_MONTH);
  System.out.println("Current date : " + day + "/" + (month + 1) + "/" + year);

Using SimpleDateFormat

output: 28/06/2012

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String sDate= sdf.format(date);

C#
Using DateTime format

output: Jun Fri 27 11:41 2012

DateTime time = DateTime.Now;              // Use current time
string format = "MMM ddd d HH:mm yyyy";    // Use this format
Console.WriteLine(time.ToString(format));

Some other patterns for DateTime
MMM : display three-letter month
ddd : display three-letter day of the WEEK
d : display day of the MONTH
HH : display two-digit hours on 24-hour scale
mm : display two-digit minutes
yyyy : display four-digit year

Single-letter format

output :
6/28/2012
Thursday, June 28, 2012
Thursday, June 28, 2012 11:36 AM
Thursday, June 28, 2012 11:36:21 AM
6/28/2012 11:36 AM
6/28/2012 11:36:21 AM
June 28
June 28
2012-06-28T11:36:21.8863219+05:30
2012-06-28T11:36:21.8863219+05:30
2012-06-28T11:36:21
11:36 AM
11:36:21 AM
2012-06-28 11:36:21Z
Thursday, June 28, 2012 6:06:21 AM
June, 2012
June, 2012

DateTime now = DateTime.Now;
Console.WriteLine(now.ToString("d"));
Console.WriteLine(now.ToString("D"));
Console.WriteLine(now.ToString("f"));
Console.WriteLine(now.ToString("F"));
Console.WriteLine(now.ToString("g"));
Console.WriteLine(now.ToString("G"));
Console.WriteLine(now.ToString("m"));
Console.WriteLine(now.ToString("M"));
Console.WriteLine(now.ToString("o"));
Console.WriteLine(now.ToString("O"));
Console.WriteLine(now.ToString("s"));
Console.WriteLine(now.ToString("t"));
Console.WriteLine(now.ToString("T"));
Console.WriteLine(now.ToString("u"));
Console.WriteLine(now.ToString("U"));
Console.WriteLine(now.ToString("y"));
Console.WriteLine(now.ToString("Y"));

Using Date strings to control the output

output:
Thursday, June 28, 2012
12:03:53 PM
6/28/2012
12:03 PM
6/28/2012 12:03:53 PM

DateTime now = DateTime.Now;
Console.WriteLine(now.ToLongDateString());
Console.WriteLine(now.ToLongTimeString());
Console.WriteLine(now.ToShortDateString());
Console.WriteLine(now.ToShortTimeString());
Console.WriteLine(now.ToString());

PHP

output : 2012-06-28 17:33:07

$date = date('Y-m-d H:i:s');
echo $date;

output : 2012/06/28 17:33:07

$date = date('Y/m/d H:i:s');
echo $date;

This time is based on the default server time zone. To get the time in a different time zone it should be set first.

date_default_timezone_set('Australia/Sydney');
$date = date('Y/m/d H:i:s');
echo $date;

JavaScript

output : Thursday, June 28, 2012

<script type="text/javascript"><!--
var now = new Date();
var Weekday = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
var Month = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
document.write(Weekday[now.getDay()]+", "+Month[now.getMonth()]+" "+now.getDate()+", "+now.getFullYear());
//--></script>

output : 6/28/2012

<script type="text/javascript"><!--
var now = new Date();
document.write((now.getMonth()+1)+"/"+now.getDate()+"/"+now.getFullYear());
//--></script>

output : 06/28/2012

<script type="text/javascript"><!--
var now = new Date();
var month = now.getMonth()+1;
if( month < 9 ) { month = "0"+month; }
var day = now.getDate();
if( day < 9 ) { day = "0"+day; }
document.write(month+"/"+day+"/"+now.getFullYear());
//--></script>

ios

 NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
 [dateFormatter setDateFormat:@"hh:mm a"];   
 NSString *str_date = [dateFormatter stringFromDate:[NSDate date]];
 NSLog(@"str_date:%@",str_date);
 
 

Tags:

Add a reminder using local notifications

This article is based on multi-tasking environment in ios sdk. There is a simple solution put in place. This solution is known as push notifications. This solution is great and all, but it still requires to have an active internet connection. Furthermore, it is little bit difficult procedure. With iOS4, Apple has introduced a new type of notification that can be scheduled to fire within the device itself. That ‘s Local Notifications. Local notifications can be scheduled on the user’s iDevice to fire at any given time.

ReminderUI.h

#import <UIKit/UIKit.h>

@interface ReminderUI : UIViewController <UITableViewDataSource,UITableViewDelegate>
{
IBOutlet UITableView *tableview;
IBOutlet UIDatePicker *datePicker;
IBOutlet UITextField *eventText;
}
@property (nonatomic, retain) IBOutlet UITableView *tableview;
@property (nonatomic, retain) IBOutlet UIDatePicker *datePicker;
@property (nonatomic, retain) IBOutlet UITextField *eventText;

-(IBAction)scheduleAlarm:(id) sender;
-(IBAction)hideKeyBoard;
-(IBAction)goBack;

@end

ReminderUI.m


#import "ReminderUI.h"
#import "GreetingAppViewController.h"

@implementation ReminderUI
@synthesize datePicker,tableview, eventText;

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

}
return self;
}

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

- (void) viewWillAppear:(BOOL)animated {
[self.tableview reloadData];
}

- (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.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
[super viewDidUnload];
datePicker = nil;
tableview = nil;
eventText = nil;
}

-(IBAction)hideKeyBoard
{
[eventText resignFirstResponder];

}

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

- (IBAction) scheduleAlarm:(id) sender
{
[eventText resignFirstResponder];

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

// Get the current date
NSDate *pickerDate = [self.datePicker date];

// Break the date up into components
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |&nbsp; NSDayCalendarUnit )
fromDate:pickerDate];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit )
fromDate:pickerDate];

// Set up the fire time
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];
// Notification will fire in one minute
[dateComps setMinute:[timeComponents minute]];
[dateComps setSecond:[timeComponents second]];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];

UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = itemDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];

// Notification details
localNotif.alertBody = [eventText text];
// Set the action button
localNotif.alertAction = @"View";

localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;

// Specify custom data for the notification
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"someValue" forKey:@"someKey"];
localNotif.userInfo = infoDict;

// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];

[self.tableview reloadData];
}

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

return 1;
}

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

return [[[UIApplication sharedApplication] scheduledLocalNotifications] count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

static NSString *CellIdentifier = @"Cell";

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

// Configure the cell...

NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
UILocalNotification *notif = [notificationArray objectAtIndex:indexPath.row];

[cell.textLabel setText:notif.alertBody];
[cell.detailTextLabel setText:[notif.fireDate description]];

return cell;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{

return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(IBAction)goBack
{
GreetingAppViewController *home= [[GreetingAppViewController alloc]initWithNibName:nil bundle:nil];
[self presentModalViewController:home animated:YES];
}

@end

Modify the appDelegate.m so that following changes will reflect.

appDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.

self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
application.applicationIconBadgeNumber = 0;

// Handle launching from a notification
UILocalNotification *localNotif =
[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotif) {
NSLog(@"Recieved Notification %@",localNotif);
}

return YES;

}

- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notif {
// Handle the notificaton when the app is running
NSLog(@"Recieved Notification %@",notif);
}



 
Leave a comment

Posted by on May 28, 2012 in iphone

 

Tags:

Send Email with attachment in iPhone

We need MessageUI framework to send email. Sending Email can not be tested using iPhone simulator. The reason is simulator does not include a mail app. The application should be installed in actual device and tested. In simulator, it displays a successful message that email has been sent but it just an indicator that no other problem with source code.


NSData *audioFile = [[NSData alloc]initWithContentsOfURL:temporaryRecFile];

MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc]init];
mailer.mailComposeDelegate = self;
[mailer setSubject:@"Greeting Message"];
NSArray *toReceipients = [NSArray arrayWithObjects:@"recepient_mail_address", nil];
[mailer setToRecipients:toReceipients];
[mailer addAttachmentData:audioFile mimeType:@"audio/caf" fileName:@"VoiceFile.caf"];
[mailer setMessageBody:@"My greetings for you" isHTML:NO];

[self presentModalViewController:mailer animated:YES];
[mailer release];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Failure" message:@"Device does not support" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];


 
Leave a comment

Posted by on May 28, 2012 in iphone

 

Tags:

Record and playback voice in iPhone

NewRecordingUI.h

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreAudio/CoreAudioTypes.h>
#import <MessageUI/MessageUI.h>

@interface NewRecordingUI : UIViewController <AVAudioRecorderDelegate,MFMailComposeViewControllerDelegate>
{
IBOutlet UIButton *playBtn;
IBOutlet UIButton *recBtn;
IBOutlet UILabel *recStstus;

BOOL isNotRecording;
NSURL *temporaryRecFile;
AVAudioRecorder *recorder;
NSTimer *sliderTimer;
}
@property(nonatomic,retain)IBOutlet UIButton *playBtn;
@property(nonatomic,retain)IBOutlet UIButton *recBtn;
@property(nonatomic,retain)IBOutlet UIButton *emailBtn;
@property(nonatomic,retain)IBOutlet UIButton *shareBtn;
@property (retain, nonatomic) IBOutlet UISlider *progressSlider;

-(IBAction)play;
-(IBAction)record;
-(IBAction)openMail:(id)sender;
@end

NewRecordingUI.m

#import "NewRecordingUI.h"
#import "GreetingAppViewController.h"
#import <MessageUI/MessageUI.h>

@implementation NewRecordingUI
@synthesize playBtn,recBtn,emailBtn,shareBtn,progressSlider;

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

- (void)viewDidLoad
{
isNotRecording = YES;
playBtn.hidden = YES;
emailBtn.hidden = YES;
shareBtn.hidden = YES;
//[playBtn setEnabled:NO];
recStstus.text = @"";

AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[audioSession setActive:YES error:nil ];

[super viewDidLoad];
}

- (void)dealloc
{
[playBtn release];
[recBtn release];
[emailBtn release];
[shareBtn release];
[super dealloc];
}

- (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.
}

#pragma mark - View lifecycle

- (void)viewDidUnload
{
NSFileManager *fileHandler = [NSFileManager defaultManager];
[fileHandler removeItemAtPath:temporaryRecFile error:nil];
[recorder dealloc];
recorder = nil;
temporaryRecFile = nil;
playBtn.hidden = YES;
emailBtn.hidden = YES;
shareBtn.hidden = YES;
}

- (void)updateSlider
{

if (!isNotRecording) {
progressSlider.value = recorder.currentTime;
}

}

-(IBAction)record
{
if(isNotRecording)
{
sliderTimer = [NSTimer scheduledTimerWithTimeInterval:0.2
target:self selector:@selector(updateSlider)
userInfo:nil repeats:YES];

progressSlider.maximumValue = 100;
//[recorder recordForDuration:10];

isNotRecording = NO;
[recBtn setTitle:@"Stop" forState:UIControlStateNormal];
//[playBtn setEnabled:NO];
playBtn.hidden = YES;
emailBtn.hidden = YES;
shareBtn.hidden = YES;
recStstus.text = @"Recording...";
temporaryRecFile = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithString:@"VoiceFile"]]];

recorder = [[AVAudioRecorder alloc]initWithURL:temporaryRecFile settings:nil error:nil];
[recorder setDelegate:self];
[recorder prepareToRecord];
[recorder record];

}
else
{
isNotRecording = YES;
[recBtn setTitle:@"Record" forState:UIControlStateNormal];
playBtn.hidden = NO;
emailBtn.hidden = NO;
shareBtn.hidden = NO;
recStstus.text = @"";
[recorder stop];
progressSlider.value = 0;
}
}

-(IBAction)play
{
progressSlider.value = 0;
sliderTimer = [NSTimer scheduledTimerWithTimeInterval:0.2
target:self selector:@selector(updateSlider)
userInfo:nil repeats:YES];

recStstus.text = @"Playing...";
[recBtn setEnabled:NO];
NSLog(@"%@",temporaryRecFile);
AVAudioPlayer *player =  [[AVAudioPlayer alloc]initWithContentsOfURL:temporaryRecFile error:nil];
player.volume = 120;
[player play];

}

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

-(IBAction)cancel
{
GreetingAppViewController * cancel= [[GreetingAppViewController alloc]initWithNibName:nil bundle:nil];
[self presentModalViewController:cancel animated:YES];
}

@end
 
2 Comments

Posted by on May 28, 2012 in iphone

 

Tags: ,

ios UIImagePicker tutorial


MyImagePickerViewController.h

#import <UIKit/UIKit.h>

@interface MyImagePickerViewController : UIViewController
<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    UIImagePickerController *ipc;
    IBOutlet UIImageView *bgImage;

}
@property (nonatomic,retain) UIImageView *bgImage;

-(IBAction) buttonClicked;

@end

MyImagePickerViewController.m

#import "MyImagePickerViewController.h"

@implementation MyImagePickerViewController


@synthesize bgImage;

-(IBAction) buttonClicked{

ipc=[[UIImagePickerController alloc]init];
ipc.delegate = self;

if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])

{
ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
}else
{
ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}

[self presentModalViewController:ipc animated:YES];

}


-(void) imagePickerControllerDidCancel:(UIImagePickerController *)picker{

//release picker

[[picker parentViewController]dismissModalViewControllerAnimated:YES];

[picker release];
}


-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{

//set image

bgImage.image = [info objectForKey:UIImagePickerControllerOriginalImage];
//release picker

[[picker parentViewController]dismissModalViewControllerAnimated:YES];

[picker release];

}







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

- (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.
}

#pragma mark - View lifecycle

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
}
*/

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

 

 
1 Comment

Posted by on May 14, 2012 in iphone

 

Tags: ,

ios database application tutorial

This is an ios application which demonstrates accessing data tier for common data manipulation tasks. So we are going to build a simple book list application.
This is the application interface.

First add sqlite3 framework to your project.

BookListViewController.h

//
//  BookListViewController.h
//  BookList
//
//  Created by Snow Leopard User on 19/04/2012.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "/usr/include/sqlite3.h"

@interface BookListViewController : UIViewController {

UITextField *txtBid;
UITextField *txtBname;
UITextField *txtBauthor;

UIButton *btnSave;
UIButton *btnFind;

UILabel *status;
NSString *databasepath;
sqlite3 *booksDB;

}
@property (nonatomic,retain) IBOutlet UITextField *txtBid;
@property (nonatomic,retain) IBOutlet UITextField *txtBname;
@property (nonatomic,retain) IBOutlet UITextField *txtBauthor;
@property (nonatomic,retain) IBOutlet UIButton *btnSave;
@property (nonatomic,retain) IBOutlet UIButton *btnFind;

@property (nonatomic,retain) IBOutlet UILabel *status;

-(IBAction) Save;
-(IBAction) Find;

@end


BookListViewController.m

//
//  BookListViewController.m
//  BookList
//
//  Created by Snow Leopard User on 19/04/2012.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "BookListViewController.h"

@implementation BookListViewController
@synthesize txtBauthor,txtBid,txtBname,btnFind,btnSave,status;

-(IBAction) Save
{
    sqlite3_stmt *statement;
    const char *dbpath=[databasepath UTF8String];

    if(sqlite3_open(dbpath, &booksDB)==SQLITE_OK)
    {
        NSString *insertSQL=[NSString stringWithFormat:@"INSERT INTO BOOKS(BookID,BookName,Author) VALUES(\"%@\",\"%@\",\"%@\")",txtBid.text,txtBname.text,txtBauthor.text];

        const char *insert_stmt=[insertSQL UTF8String];

        sqlite3_prepare_v2(booksDB, insert_stmt, -1, &statement, NULL);

        if(sqlite3_step(statement)==SQLITE_DONE)
        {
            status.text=@"Book Added";
            txtBid.text=@"";
            txtBauthor.text=@"";
            txtBname.text=@"";

        }else
        {
            status.text=@"Failed to add Book";
        }
        sqlite3_finalize(statement);
        sqlite3_close(booksDB);
    }

}

-(IBAction) Find
{
    const char *dbpath=[databasepath UTF8String];
    sqlite3_stmt *statement;

    if(sqlite3_open(dbpath, &booksDB)==SQLITE_OK)
    {
        NSString *querySQL=[NSString stringWithFormat:@"SELECT BookID,BookName FROM books WHERE BookID=\"%@\"",txtBid.text];

        const char *query_stmt=[querySQL UTF8String];

        if(sqlite3_prepare_v2(booksDB, query_stmt, -1, &statement, NULL)==SQLITE_OK)
        {
            if(sqlite3_step(statement)==SQLITE_ROW)
            {
                NSString *addressField=[[NSString alloc] initWithUTF8String:(const char*)sqlite3_column_text(statement, 0)];

                txtBname.text=addressField;

                NSString *phoneField=[[NSString alloc] initWithUTF8String:(const char*)sqlite3_column_text(statement, 1)];

                txtBname.text=phoneField;

                status.text=@"Match Found";
                txtBname.text=@"";
                txtBauthor.text=@"";

            }
            sqlite3_finalize(statement);
        }
        sqlite3_close(booksDB);

    }

}

- (void)dealloc
{
    [txtBid release];
    [txtBname release];
    [txtBauthor release];

    [super dealloc];
}

- (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.
}

#pragma mark - View lifecycle

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{

    NSString *docsDir;
    NSArray *dirPaths;

    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    docsDir =[dirPaths objectAtIndex:0];

    databasepath = [[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:@"books.db"]];

    NSFileManager *filemgr=[NSFileManager defaultManager];

    if([filemgr fileExistsAtPath:databasepath]==NO)
    {
        const char *dbpath=[databasepath UTF8String];

        if(sqlite3_open(dbpath, &booksDB)==SQLITE_OK)
        {
            char *errMsg;
            const char *sql_stmt="CREATE TABLE IF NOT EXISTS BOOKS(ID INTEGER PRIMARY KEY AUTOINCREMENT,BookID TEXT,BookName TEXT,Author TEXT)";

            if(sqlite3_exec(booksDB, sql_stmt, NULL, NULL, &errMsg)!=SQLITE_OK)
            {
                status.text=@"Failed to create table";
            }
            sqlite3_close(booksDB);

        }else
        {
            status.text=@"Failed to Open/Create Database";
        }

    }
    [filemgr release];

    [super viewDidLoad];
}

- (void)viewDidUnload
{

    [super viewDidUnload];

    self.txtBid=NULL;
    self.txtBname=NULL;
    self.txtBauthor=NULL;
    self.status=NULL;
    // 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

 

 
Leave a comment

Posted by on May 14, 2012 in iphone

 

Tags: , ,