我希望我的闹钟每天在选定的时间重复,并在 iPhone 中具有贪睡功能

Posted

技术标签:

【中文标题】我希望我的闹钟每天在选定的时间重复,并在 iPhone 中具有贪睡功能【英文标题】:i want my alarm to be repeat every day at selected time with snooze functionality in iPhone 【发布时间】:2011-10-31 12:14:29 【问题描述】:

我想在我的闹钟应用程序中具有重复功能,但我无法做到。任何人都可以以任何方式帮助我......比如伪代码或告诉如何做,或一些教程等。

我的闹钟没有在正确的时间调用,它总是延迟一段时间,有时延迟 50 秒,哈哈。应该为此做些什么。

这是我到目前为止所做的代码......

@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

【问题讨论】:

【参考方案1】:

使用此代码可能对您有帮助...

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];

它显示设置特定日期和时间导入 EventKit 框架的警报

【讨论】:

感谢您的代码...让我检查一下,如果它有效,我很乐意接受答案.. :) 什么是 EKEventScore、EKEvent 和 EKSpanThisEvent?? #import 是否有人对我的问题有任何看法。除了投反对票之外,任何人都可以回答我的问题吗?和@516:-谢谢你的代码对我有用......我在等待一些答案,如果他们不来,那么稍后我会接受答案,因为我的问题仍然没有完全得到回答......

以上是关于我希望我的闹钟每天在选定的时间重复,并在 iPhone 中具有贪睡功能的主要内容,如果未能解决你的问题,请参考以下文章

每天在特定时间设置重复闹钟

如何在iphone中设置选定日期的闹钟?

如何在 ios 中的选定工作日(星期一、星期日)设置闹钟。 (本地通知)

显示每天 iphone sdk 选定时间的本地通知

Android:除周末外,每天设置闹钟

UITableView 多选