日期选择器精确到分后设置本地通知有延迟数秒的问题

来源:互联网 发布:淘宝详情模板 编辑:程序博客网 时间:2024/05/18 02:20

在不需要做远程推送的情况下,可以在APP中设定本地通知,类似闹铃提醒的功能,在项目中遇到这样一个问题,提醒时间设置为分,但是每次都会出现延迟问题,或则几秒,或则几十秒,先看具体实现代码:

1,这是一个日期选择器部分代码:

UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, H-216+20, 320, 216)];    datePicker.backgroundColor = [UIColor whiteColor];    [datePicker setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];        //注意:只能设置比当前时间后的时间,且间隔为2分钟    [datePicker setMinimumDate:datePicker.date];    [datePicker setMinuteInterval:2];        [datePicker setDatePickerMode:UIDatePickerModeDateAndTime];    if (!selectDateStr) {        selectDateStr =  [[self dateFormatter] stringFromDate:datePicker.date];    }else{        // 设置指定时间        NSString *tempStr = [selectDateStr substringToIndex:17];// @"2014年06月12日 16:38";        NSDateFormatter *formatter = [self dateFormatter];        [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm"];        NSDate *tempDate = [formatter dateFromString:tempStr];        [datePicker setDate:tempDate animated:YES];    }        [datePicker addTarget:self action:@selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];    [subView addSubview:datePicker];        [self.view.window addSubview:subView];

回调函数获取选中的时间:

-(void)datePickerValueChanged:(id)sender{    UIDatePicker *datePicker = (UIDatePicker*)sender;    _selectDate = datePicker.date;    NSString *dateAndTime =  [[self dateFormatter] stringFromDate:_selectDate];    NSLog(@"dateAndTime:%@",dateAndTime);    selectDateStr =dateAndTime;}

这里先取到了日期时间,打印:
(lldb) po _selectDate2014-07-24 05:40:32 +0000


2,设置本地通知。部分代码:

-(void)settingLocalNotification{        UILocalNotification *notification = [[UILocalNotification alloc] init];  /*问题所在,之前直接将上面的<span style="font-family: Arial, Helvetica, sans-serif;">_selectDate 给了firedate ,造成了延时秒的问题,需要再次格式化到秒,再转为date</span>*/    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];    [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm"];    NSMutableArray *fireArr = [[selectDateStr componentsSeparatedByString:@" "] mutableCopy];    [fireArr removeLastObject];    NSString *fireStr = [fireArr componentsJoinedByString:@" "];    NSDate *fireDate = [formatter dateFromString:fireStr];        notification.fireDate = fireDate;    notification.timeZone = [NSTimeZone localTimeZone];    notification.repeatInterval = 0;    notification.alertBody = [NSString stringWithFormat:@"%@\n%@",selectDateStr, self.title];    notification.applicationIconBadgeNumber = 1;    notification.soundName = UILocalNotificationDefaultSoundName;      notification.userInfo = self.item;// userDict;    [[UIApplication sharedApplication] scheduleLocalNotification:notification];}


如同上面的解释,不能直接给这个选择器的日期,需要先格式化成字符串,然后去掉秒后再次转为date类型给本地通知设置定时,就避免了日期里面没有秒列表,但是却有延迟问题,隐藏了秒的存在。


推荐:微推 -梦工厂


0 0
原创粉丝点击