1. 程式人生 > >iOS本地鬧鐘提醒實現

iOS本地鬧鐘提醒實現

有的時候我們在應用中需要做一個類似於鬧鐘提醒的功能,在每週的特定的幾天中,在固定時間進行提醒。比如每週一到週五下午六點,需要吃藥的時間就彈窗提醒:快去吃藥!不要放棄治療!

本地固定時間提醒,需要用到 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;
        }
    }