我需要从 UIDatePicker 获取日期和时间,并在该日期和时间到达时触发本地通知。我该怎么做呢?谢谢!
问问题
1592 次
2 回答
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];
于 2013-03-13T05:33:17.307 回答
1
用于self.datePicker.date
存储目标日期和时间。
然后创建一个 NSTimer,每毫秒轮询一次以检查当前日期是否等于目标日期。当两者相等时,显示警报视图。
于 2013-03-12T17:12:39.153 回答