我想根据用户输入设置每日闹钟。就像用户将从日期选择器中选择时间" 10:30",然后我需要每天在那个时间设置闹钟。我写了以下代码:
func setAlarmAtTime(#time:NSString, withMessage message:NSString){
var loacalNotification = UILocalNotification();
var calendar = NSCalendar.currentCalendar();
calendar.timeZone = NSTimeZone.localTimeZone()
var components = calendar.components(NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.DayCalendarUnit, fromDate: NSDate.date());
NSLog("%@",NSDate.date())
NSLog(time);
var timeComponents = time.componentsSeparatedByString(":");
components.hour = timeComponents[0].integerValue;
components.minute = timeComponents[1].integerValue;
if components.isValidDateInCalendar(calendar){
var fireDate = calendar.dateFromComponents(components);
NSLog("%@",fireDate!);
loacalNotification.repeatInterval = NSCalendarUnit.CalendarUnitDay;
loacalNotification.timeZone = NSTimeZone.localTimeZone();
loacalNotification.fireDate = fireDate;
loacalNotification.repeatInterval = NSCalendarUnit.CalendarUnitDay;
loacalNotification.soundName = UILocalNotificationDefaultSoundName;
loacalNotification.alertBody = message;
}
但它显示基于时区的不同时间以下是我尝试在6:40设置闹钟时的行为:
Current Date: 2014-08-12 12:07:21 +0000
Alarm Time: 6:40
Fire Date: 2014-08-12 01:10:00 +0000
我尝试将时区设置为本地和当前,但没有任何作用:(
答案 0 :(得分:1)
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"dd-MMM-yyyy HH:mm"];
NSDate *reminderDate = [df dateFromString:self.lblDate.text];
// Schedule the notification
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = reminderDate;
localNotification.alertBody = self.txtName.text;
localNotification.alertAction = @"Show me the item";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.soundName =@"sound.mp3";
NSMutableDictionary *notifyDict = [[NSMutableDictionary alloc] init];
[notifyDict setValue:self.lblType.text forKey:NOTIFICATION_TYPE];
[notifyDict setValue:self.txtName.text forKey:NOTIFICATION_TITLE];
if (![self.tvDescription.text isEqualToString:@"Write Description"]) {
[notifyDict setValue:self.tvDescription.text forKey:NOTIFICATION_DESCRIPTION];
}
[notifyDict setValue:self.lblDate.text forKey:NOTIFICATION_DATE];
localNotification.userInfo = notifyDict;
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[self.navigationController popViewControllerAnimated:YES];
[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadData" object:self];
答案 1 :(得分:0)
给出的时间是格林威治标准时间(GMT)
我们只需要设置
localNotification.timeZone = [NSTimeZone systemTimeZone];
因为它代表您的设备或系统时区并安排您的应用
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];