iOS创建本地通知和删除对应的通知,工作日通知

本文的代码主要是:创建本地通知,删除对应的本地通知,创建工作日闹钟

直接上代码:

//
//  ViewController.m
//  LocalNSNotification
//
//  Created by wusiping on 16/1/27.
//  Copyright © 2016年 wusiping. All rights reserved.
//

#import "ViewController.h"
#define LOCAL_NOTIFY_SCHEDULE_ID @"hahahhahahhah"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    UIButton *createBtn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    [createBtn setTitle:@"创建通知" forState:UIControlStateNormal];
    createBtn.titleLabel.textColor = [UIColor blackColor];
    createBtn.backgroundColor = [UIColor lightGrayColor];
    [createBtn addTarget:self action:@selector(createNSNotification) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:createBtn];
    
    UIButton *cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(100, 300, 100, 100)];
    [cancelBtn setTitle:@"删除通知" forState:UIControlStateNormal];
    cancelBtn.titleLabel.textColor = [UIColor blackColor];
    cancelBtn.backgroundColor = [UIColor lightGrayColor];
    [cancelBtn addTarget:self action:@selector(cancelNSNotification) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancelBtn];

}


- (NSDate *)getCurrrentTimeToSS
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [formatter dateFormat];
    [NSDate date];
    return [NSDate date];
    
}

- (void)createNSNotification{
    
    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    if (localNotification == nil) {
        return;
    }
    //设置本地通知的触发时间(如果要立即触发,无需设置),这里设置为20妙后
    localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:20];
    //设置本地通知的时区
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    //设置通知的内容
    localNotification.alertBody = @"hahhah";
    //设置通知动作按钮的标题
    localNotification.alertAction = @"查看";
    //设置提醒的声音,可以自己添加声音文件,这里设置为默认提示声
    localNotification.soundName = UILocalNotificationDefaultSoundName;
    //设置通知的相关信息,这个很重要,可以添加一些标记性内容,方便以后区分和获取通知的信息
    NSDictionary *dict =[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:9529],@"nfSignInkey",nil];
    [localNotification setUserInfo:dict];

    // ios8后,需要添加这个注册,才能得到授权
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
                                                                                 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        // 通知重复提示的单位,可以是天、周、月
        localNotification.repeatInterval = NSCalendarUnitDay;
    } else {
        // 通知重复提示的单位,可以是天、周、月
        localNotification.repeatInterval = NSDayCalendarUnit;
    }

    //在规定的日期触发通知
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

}


/**
 *  删除当前的通知
 */

- (void)cancelNSNotification{
    
    //   手动删除通知
    //   这里我们要根据我们添加时设置的key和自定义的ID来删
        NSArray *narry=[[UIApplication sharedApplication] scheduledLocalNotifications];
        NSUInteger acount=[narry count];
        if (acount>0)
        {
            // 遍历找到对应nfkey和notificationtag的通知
            for (int i=0; i<acount; i++)
            {
                UILocalNotification *myUILocalNotification = [narry objectAtIndex:i];
                NSDictionary *userInfo = myUILocalNotification.userInfo;
                NSNumber *obj = [userInfo objectForKey:@"nfSignInkey"];
                int mytag=[obj intValue];
                if (mytag==9529)
                {
                    // 删除本地通知
                    [[UIApplication sharedApplication] cancelLocalNotification:myUILocalNotification];
                    break;
                }
            }
        }
}

@end

大家可能会遇到工作日闹钟这种需求:
 if ([cycle isEqual:@"工作日"]) {//如果是工作日闹钟
            NSDate *now=select;//当前时间
            NSCalendar *gregorian = [NSCalendar currentCalendar];
            NSDateComponents *dateComps = [gregorian components:NSWeekdayCalendarUnit fromDate:now];
            NSInteger daycount = [dateComps weekday]-2;
            NSDate *weekdaybegin=[now addTimeInterval:-daycount*60*60*24];
            for (int i=0;i<5;i++) {//创建5个通知:星期一到星期五
                NSDate *now= [weekdaybegin addTimeInterval:i*60*60*24];
                [self creatmessage:now];
            }
   }

-(void)creatmessage:(NSDate *)new
{
    UILocalNotification *notification=[[UILocalNotification alloc] init];
    if (notification!=nil && select!=nil &&cycle.length > 0 &&key.intValue==1)
    {
        //触发通知时间
        //[self cancelUILocalNotification];
        NSDate *now= new;
        NSLog(@"%@",now);
        NSDate *today = [self getCurrrentTimeToDay];
        BOOL isSameDay = [self isSameDay:now date2:today];
        if (isSameDay == YES){//特殊需求..这个不要管
            //今天所在的星期X,延迟一个礼拜触发。比如今天是星期三,那下个礼拜三才开始闹钟。明天是星期四,星期四的闹钟还是明天就触发

            now = [NSDate dateWithTimeInterval:24*60*60*7 sinceDate:now];
            
        }
        notification.fireDate=now;
        notification.timeZone=[NSTimeZone defaultTimeZone];
        notification.repeatInterval = kCFCalendarUnitWeek;
        notification.soundName=@"铃声.m4r";
        notification.alertBody=@"今天iSite签到没?千万不要忘了哦!";
        notification.alertAction=NSLocalizedString(@"今天iSite签到没?千万不要忘了哦!", nil);
        NSDictionary *dict =[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:9529],@"nfSignInkey",nil];
        [notification setUserInfo:dict];
        
        // 启用这个通知
        [[UIApplication sharedApplication]   scheduleLocalNotification:notification];
    }
    
}

 

 

 

posted @ 2016-01-27 10:02  ID_超电磁炮  阅读(1947)  评论(0编辑  收藏  举报