RSS

Monthly Archives: May 2012

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: ,

Display date in different formats with PHP

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

Sample output : 2012-05-20 11:33:44

 
Leave a comment

Posted by on May 20, 2012 in PHP

 

Tags:

Display Near by places with Google Places API

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Google Maps JavaScript API v3 Example: Place Search</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true&libraries=places"></script>

<style type="text/css">
#map {
height: 400px;
width: 600px;
border: 1px solid #333;
margin-top: 0.6em;
}
</style>

<script type="text/javascript">
var map;
var infowindow;

function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);

map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});

var request = {
location: pyrmont,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}

function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}

function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});

google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}

google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
<div id="text">
<pre>
var request = {
location: new google.maps.LatLng(-33.8665433, 151.1956316),
radius: 500,
types: ['store']
};
</pre>
</body>
</html>


 

 
2 Comments

Posted by on May 17, 2012 in Geo Programming, JavaScript

 

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: , ,