本地通知



    - (void)scheduleLocalNotification {

        

        // 初始化本地通知

        UILocalNotification *localNotification = [[UILocalNotification alloc] init];

        

        // 通知触发时间

        localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:3];

        // 触发后,弹出警告框中显示的内容

        localNotification.alertBody = @"弹出警告框中显示的内容";

        // 触发时的声音(这里选择的系统默认声音)

        localNotification.soundName = UILocalNotificationDefaultSoundName;

        // 触发频率(repeatInterval是一个枚举值,可以选择每分、每小时、每天、每年等)

        localNotification.repeatInterval = NSCalendarUnitDay;

        // 需要在App icon上显示的未读通知数(设置为1时,多个通知未读,系统会自动加1,如果不需要显示未读数,这里可以设置0

        localNotification.applicationIconBadgeNumber = 1;

        // 设置通知的id,可用于通知移除,也可以传递其他值,当通知触发时可以获取

        localNotification.userInfo = @{@"id" : @"notificationId1"};

        

        // 注册本地通知

        [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

    }



当本地通知触发后,需要在AppDelegate中进行接收并做相应处理。在AppDelegate中,实现以下方法:

    - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {

        

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:notification.alertBody delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil];

        [alert show];

    }


移除本地通知的方法有两种,一种是全部移除:


[[UIApplication sharedApplication] cancelAllLocalNotifications];



一种是按照id来移除,这个id就是在注册通知时,写的id:


    - (void)removeLocalNotification {

        

        // 取出全部本地通知

        NSArray *notifications = [UIApplication sharedApplication].scheduledLocalNotifications;

        // 设置要移除的通知id

        NSString *notificationId = @"notificationId1";

        

        // 遍历进行移除

        for (UILocalNotification *localNotification in notifications) {

            

            // 将每个通知的id取出来进行对比

            if ([[localNotification.userInfo objectForKey:@"id"] isEqualToString:notificationId]) {

                

                // 移除某一个通知

                [[UIApplication sharedApplication] cancelLocalNotification:localNotification];

            }

        }

    }



   注意事项

   1. 如果需要做一个闹钟或备忘录之类的应用,则将时间作为fireDate,触发之后可以进行移除;

    

   2. 一个App中,本地通知数量最多64个,不用的通知要及时移除;

    

   3. 如果通知的时间是后台返回的,那每次需要将通知全部移除,再添加新的。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值