设置用户输入的本地通知时间



我正在研究 loacl 通知通知成功。 但我不想为来自选择器的通知设置触发日期 我想设置用户想要的通知触发时间。 我已经给出了文本字段来输入时间,并希望根据用户时间设置触发日期。

假设用户输入下午 1:00,

那么通知在今天下午 1:00 发出

下面是我的代码——

NSCalendar *calendar = [NSCalendar currentCalendar]; // gets default calendar
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[NSDate date]]; // gets the year, month, day,hour and minutesfor today's date
[components setHour:txtStartTime.text];
//   [components setMinute:12];
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = [calendar dateFromComponents:components];
localNotification.timeZone = [NSTimeZone localTimeZone];
localNotification.alertBody = txtSubjectName.text;
localNotification.alertAction = @"Lecture Notification";
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    [self dismissViewControllerAnimated:YES completion:nil];
您可以使用

NSDateFormatter将字符串转换为 NSDate,然后将该 NSDate 用作 fireDate。但是,只有当用户完全按预期输入日期时,它才能正常工作。以下是其工作原理的代码示例:

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd hh:mm:ss a"];
NSDate *myDate = [df dateFromString: myDateAsAStringValue];

这是一个网站,显示了可用的不同日期格式模式,以便您可以创建自己的输入样式:http://waracle.net/iphone-nsdateformatter-date-formatting-table/

您应该使用UIDatePicker让用户轻松输入日期和时间。这是一个解释如何使用它的教程:http://www.edumobile.org/iphone/iphone-programming-tutorials/add-datepicker-programmatically-and-display-date-in-iphone/

最新更新