您的位置:首页 > 移动开发 > IOS开发

iOS本地闹钟提醒实现

2015-06-15 15:57 591 查看
有的时候我们在应用中需要做一个类似于闹钟提醒的功能,在每周的特定的几天中,在固定时间进行提醒。比如每周一到周五下午六点,需要吃药的时间就弹窗提醒:快去吃药!不要放弃治疗!

本地固定时间提醒,需要用到 UILocalNotification

如果只是添加一次,并且设置提醒的周期为 NSCalendarUnitWeekOfYear ,那么就是每周只提醒一次。所以如果要达到每周固定星期几提醒则需要添加提醒天的次数,比如周一到周五提醒那么就需要添加五次,每个提醒的间隔都为一个星期。这样就可以做到每周固定星期提醒了。

for(id day in _weekArr) {// _weekArr 为周一到周日需要提醒的星期

UILocalNotification* beginLocalNotification = [[UILocalNotification alloc] init];
NSDictionary* beginInfo = [NSDictionary dictionaryWithObject:kLocalNoti forKey:@"beginNoti"];
beginLocalNotification.userInfo = beginInfo;
beginLocalNotification.fireDate = [dateFormatter dateFromString:[NSString stringWithFormat:@"2015-06-%d %@:00",15+[day integerValue]-1,_beginTime]];// 在过去的某个星期内添加需要的本地提醒。并且设置提醒间隔为NSCalendarUnitWeekOfYear,如果添加在未来,那么提醒不会发生。
beginLocalNotification.alertBody = @"该吃药啦!";
beginLocalNotification.soundName = @"ping.caf";
beginLocalNotification.timeZone = [NSTimeZone defaultTimeZone];
beginLocalNotification.alertAction = @"不要忘记吃药哦!";
beginLocalNotification.repeatInterval =NSCalendarUnitWeekOfYear;// 每周循环提醒
[[UIApplication sharedApplication] scheduleLocalNotification:beginLocalNotification];
}


取消提醒比较简单,如果想取消所有的本地提醒:

[[UIApplication sharedApplication] cancelAllLocalNotifications];


取消特定的提醒:

NSArray *narry=[[UIApplication sharedApplication] scheduledLocalNotifications];
NSUInteger acount=[narry count];
if (acount<1) {
return false;
}
for (int i=0; i<acount; i++) {
UILocalNotification *myUILocalNotification = [narry objectAtIndex:i];
NSDictionary *userInfo = myUILocalNotification.userInfo;
NSString *obj = [userInfo objectForKey:@"beginNoti"];

if ([obj isEqualToString @"kLocalNoti "]) {
[[UIApplication sharedApplication] cancelLocalNotification:myUILocalNotification];
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: