mAc
mAc

Reputation: 2514

i want my alarm to be repeat every day at selected time with snooze functionality in iPhone

i wanted to have repetition functionality in my Alarm clock app, in which i am unable to do.Can anyone help me out in any way.. like psuedo code or telling how to do, or some tutorial etc.

One more thing my Alarm is not invoking at correct time, it always delays by some time sometimes by 50 sec, lol. what should be done for that.

Here is my code what i have done till now...

@implementation The420DudeAppDelegate

@synthesize window;
@synthesize viewController,soundFlag;

NSString *kRemindMeNotificationDataKey = @"kRemindMeNotificationDataKey";

#pragma mark -
#pragma mark === Application Delegate Methods ===
#pragma mark -



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    soundFlag = 0;

    Class cls = NSClassFromString(@"UILocalNotification");
    if (cls) {
        UILocalNotification *notification = [launchOptions objectForKey:
                                             UIApplicationLaunchOptionsLocalNotificationKey];

        if (notification) {
            NSString *reminderText = [notification.userInfo 
                                      objectForKey:kRemindMeNotificationDataKey];
            [viewController showReminder:reminderText];
        }
    }

    application.applicationIconBadgeNumber = 0;

    [window addSubview:viewController.view];
    [self.window makeKeyAndVisible];

    return YES;
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    application.applicationIconBadgeNumber = 0;
    soundFlag = 1;
}

- (void)application:(UIApplication *)application 
didReceiveLocalNotification:(UILocalNotification *)notification {

    application.applicationIconBadgeNumber = 0;
    NSString *reminderText = [notification.userInfo
                              objectForKey:kRemindMeNotificationDataKey];
    [viewController showReminder:reminderText];
}

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


@end




@class The420DudeAppDelegate;

@interface The420DudeViewController : UIViewController<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate> {

    IBOutlet UINavigationBar *titleBar;
    IBOutlet UIButton *setAlarmButton;
    IBOutlet UIDatePicker *selectTimePicker;
    AVAudioPlayer *player;
    IBOutlet UITableView *reminderTable;
    IBOutlet UITextField *reminderTextField;

    The420DudeAppDelegate *appDelegate;
}

@property(nonatomic, retain) IBOutlet UINavigationBar *titleBar;
@property(nonatomic, retain) IBOutlet UIButton *setAlarmButton;
@property(nonatomic, retain) IBOutlet UIDatePicker *selectTimePicker;
@property(nonatomic, retain) IBOutlet UITableView *reminderTable;
@property(nonatomic, retain) IBOutlet UITextField *reminderTextField;

-(IBAction)onTapSetAlarm;
- (void)showReminder:(NSString *)text;

@end



@implementation The420DudeViewController

@synthesize titleBar,setAlarmButton,selectTimePicker,reminderTable,reminderTextField;


#pragma mark -
#pragma mark === Initialization and shutdown ===
#pragma mark -

- (void)viewDidLoad {
    [super viewDidLoad];

    NSDate *now = [NSDate date];

    [selectTimePicker setDate:now animated:YES];

    NSLog(@"IN Did Load === %@",now);
    appDelegate = (The420DudeAppDelegate *)[[UIApplication sharedApplication] delegate];

    reminderTable.dataSource = self;
    reminderTable.delegate = self;
    reminderTextField.delegate = self;
}

- (void)viewDidUnload {

    [super viewDidUnload];
    self.setAlarmButton = nil;
    self.selectTimePicker = nil;
    self.reminderTextField = nil;

}

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

/*
    NSString *path = [[NSBundle mainBundle]pathForResource:@"Song1" ofType:@"mp3"];
    NSURL *url = [NSURL fileURLWithPath:path];

    player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
    [player play];
*/
}

-(IBAction)onTapSetAlarm
{
    NSLog(@"textField =  %@",reminderTextField.text);
    [reminderTextField resignFirstResponder];
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
//************************

    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

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

    NSLog(@"In Button Action ==== %@",pickerDate);

    // Break the date up into components
    NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  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]];
    NSLog(@"%d",dateComps.day);
    [dateComps setMonth:[dateComponents month]];
    NSLog(@"%d",dateComps.month);
    [dateComps setYear:[dateComponents year]];
    NSLog(@"%d",dateComps.year);
    [dateComps setHour:[timeComponents hour]];
    NSLog(@"%d",dateComps.hour);
    // Notification will fire in one minute
    [dateComps setMinute:[timeComponents minute]];
    NSLog(@"%d",dateComps.minute);
    [dateComps setSecond:[timeComponents second]];
    NSLog(@"%d",dateComps.second);

    NSDate *itemDate = [calendar dateFromComponents:dateComps];
    [dateComps release];

    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    if (localNotif == nil)
        return;
    localNotif.fireDate = itemDate;
    NSLog(@"%@",localNotif.fireDate);

    localNotif.timeZone = [NSTimeZone defaultTimeZone];

    // Notification details
    localNotif.alertBody = reminderTextField.text;
    // Set the action button
    localNotif.alertAction = @"Show me";

    localNotif.soundName = @"jet.wav";
    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.reminderTable reloadData];


//************************
    /*
    Class cls = NSClassFromString(@"UILocalNotification");
    if (cls != nil) {

        UILocalNotification *notif = [[cls alloc] init];
        notif.fireDate = [selectTimePicker date];
        notif.timeZone = [NSTimeZone defaultTimeZone];

        notif.alertBody = @"Did you forget something?";
        notif.alertAction = @"Show me";
        notif.repeatInterval = NSDayCalendarUnit;

        notif.soundName = @"jet.wav";

        notif.applicationIconBadgeNumber = 1;

        NSDictionary *userDict = [NSDictionary dictionaryWithObject:reminderTextField.text
                                                             forKey:kRemindMeNotificationDataKey];
        notif.userInfo = userDict;

        [[UIApplication sharedApplication] scheduleLocalNotification:notif];
        [notif release];
    }
     */

/*
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm a"];

NSDate *selectedDate = [[NSDate alloc] init];
selectedDate = [selectTimePicker date];

NSString *theTime = [timeFormat stringFromDate:selectedDate];

UIAlertView *alert = [[UIAlertView alloc]
                      initWithTitle:@"Time selected" message:theTime delegate:nil cancelButtonTitle:@"YES" otherButtonTitles:nil];

[alert show];
[alert release];
//  [timeFormat release];
//  [selectedDate release];

 */
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return [[[UIApplication sharedApplication] scheduledLocalNotifications] count];
}


#pragma mark -
#pragma mark === Public Methods ===
#pragma mark -

- (void)showReminder:(NSString *)text {
    if(appDelegate.soundFlag == 0)
    {
        NSString *path = [[NSBundle mainBundle]pathForResource:@"jet" ofType:@"wav"];
        NSURL *url = [NSURL fileURLWithPath:path];

        player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
        [player play];
    }
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Reminder" 
                                                        message:reminderTextField.text delegate:self
                                              cancelButtonTitle:nil
                                              otherButtonTitles:@"Ok",nil];
    [alertView show];
    [alertView release];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 0)
    {
        NSLog(@"Hello in 0");
    }
    else
    {
        NSLog(@"Hello in 1");
    }
    [player stop];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//  NSLog(@"%@",[[[UIApplication sharedApplication] scheduledLocalNotifications] count]);
//  return [[[UIApplication sharedApplication] scheduledLocalNotifications] count];
    return 5;

}

- (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];
//  NSLog(@"%@",[[[UIApplication sharedApplication] scheduledLocalNotifications] count]);

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

    return cell;
}

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

- (void)dealloc {
    [super dealloc];
    [titleBar release];
    [setAlarmButton release];
    [selectTimePicker release];
}

@end

Upvotes: 1

Views: 3182

Answers (1)

Chithri Ajay
Chithri Ajay

Reputation: 917

use this code may be it's help to u...

EKEventStore *eventStore = [[EKEventStore alloc] init];

    EKEvent *event  = [EKEvent eventWithEventStore:eventStore];
    event.title     = @"EVENT TITLE";

    NSDateFormatter* df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"MM/dd/yyyy"];
     event.startDate = [df dateFromString:@"your selected date"];


    NSLog(@"start date is %@",event.startDate);
    event.endDate   = [[NSDate alloc] initWithTimeInterval:600 sinceDate:event.startDate];
    //NSLog(@"end date %@",event.endDate);

    [event setCalendar:[eventStore defaultCalendarForNewEvents]];
    //NSLog(@"events are %@",event);
    //NSLog(@"events are %@",eventStore);
    NSError *err;
    [eventStore saveEvent:event span:EKSpanThisEvent error:&err];

it show alarm for set specific date and time import EventKit framework

Upvotes: 3

Related Questions