如何从UIDatePicker获取日期和时间并在该日期到达时通知用户?

时间:2013-03-12 17:08:00

标签: iphone xcode uidatepicker

我需要从UIDatePicker获取日期和时间,并在该日期和时间到达时触发本地通知。我该怎么做呢?谢谢!

2 个答案:

答案 0 :(得分:3)

使用此代码

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

    // Get the current date
    NSDate *pickerDate = your date from date picker;

    // 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]];
    [dateComps setMonth:[dateComponents month]];
    [dateComps setYear:[dateComponents year]];
    [dateComps setHour:[timeComponents hour]];
    [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 = @"Write your text here";
    // Set the action button
    localNotif.alertAction = @"View";

    localNotif.soundName = UILocalNotificationDefaultSoundName;


    // Specify custom data for the notification
    NSStream *str=[NSString stringWithFormat:@"%d",cId];
    NSDictionary *infoDict = [NSDictionary dictionaryWithObject:str forKey:@"NotificationDate"];
    localNotif.userInfo = infoDict;

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


    NSLog(@"The notifications are:%@",[[UIApplication sharedApplication]scheduledLocalNotifications]);
    NSLog(@"The %@",localNotif.userInfo);

    [localNotif release];

答案 1 :(得分:1)

使用self.datePicker.date存储目标日期和时间。

然后制作一个NSTimer,它将轮询每个miilisecond以检查当前日期是否等于目标日期。两者都变得相等然后显示警报视图。