本地通知

AppDelegate.m

// 只有当应用在前台时,该方法才会被调用
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification*)notification{
    // 如果应用程序在前台,将应用程序图标上红色徽标中数字设为0
    application.applicationIconBadgeNumber = 0;
    // 使用UIAlertView显示本地通知的信息
    [[[UIAlertView alloc] initWithTitle:@"收到通知"message:notification.alertBody delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] show];
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // 应用程序再次进入前台时,将应用程序徽标设置0
    application.applicationIconBadgeNumber = 0;
}

ViewController.m

- (void)viewDidLoad
{
UIBarButtonItem *tongzhiBtn = [[UIBarButtonItem alloc]initWithTitle:@"通知" style:UIBarButtonItemStylePlain target:self action:@selector(tongzhi)];
    self.navigationItem.leftBarButtonItem = tongzhiBtn;
    UIBarButtonItem *exittongzhi = [[UIBarButtonItem alloc]initWithTitle:@"取消通知" style:UIBarButtonItemStylePlain target:self action:@selector(exittongzhi)];
    
    self.navigationItem.rightBarButtonItem = exittongzhi;
}
//通知按钮触发事件
- (void)tongzhi
{
    if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)])
    {
        [[UIApplication sharedApplication]registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
    }
    //注册本地通知
    UILocalNotification *notifi = [[UILocalNotification alloc]init];
    //通知触发时间
    notifi.fireDate = [NSDate dateWithTimeIntervalSinceNow:3];
    //设置通知的时区
    notifi.timeZone = [NSTimeZone defaultTimeZone];
    //设置重复发生的时间间隔
    notifi.repeatInterval = kCFCalendarUnitHour;
    //设置通知声音
    notifi.soundName = @"123.mp3";
    //image
    notifi.alertLaunchImage = @"logo.png";
    
    notifi.alertAction = @"打开";
    //设置通知是否可以显示
    notifi.hasAction = YES;
    //alertBody
    notifi.alertBody = @"亲,好几天不登录,Tom猫想念你了!";
    //设置应用程序徽标数字
    notifi.applicationIconBadgeNumber = 1;
    NSDictionary *info = @{@"lalalalala.org":@"key"};
    notifi.userInfo = info;
    //调度通知
    [app scheduleLocalNotification:notifi];
}
//取消通知按钮触发事件
- (void)exittongzhi
{       // 获取所有处于调度中本地通知数组
        NSArray *localArray = [app scheduledLocalNotifications];
        if (localArray)
        {
            for (UILocalNotification *noti in localArray)
            {
                NSDictionary *dic = noti.userInfo;
                if (dic)
                {
                    // 如果找到要取消的通知
                    NSString *inKey = [dic objectForKey:@"key"];
                    if ([inKey isEqualToString:@"lalalalala.org"])
                    {
                        // 取消调度该通知
                        [app cancelLocalNotification:noti];  // ②
                    }
                }
            }
        }
}


你可能感兴趣的:(本地通知)