iOS开发:本地通知(推送)

主要步骤

/*
        创建本地通知的步骤:
     1.创建UILocalNotification:
     2.设置处理通知的时间fireDate
     3.配置通知的内容:通知主体、通知声音、图标数字等
     4.配置通知传递的自定义数据参数userInfo
     5.调用通知,可以使用scheduleLocalNotification:按计划调度一个通知,也可以使用presentLocalNotificationNow立即调用通知

     */

1.开启权限


    if ([[UIApplication sharedApplication] currentUserNotificationSettings].types != UIUserNotificationTypeNone) {
     //开启了,直接调用私有方法创建推送   
        [self addLocalNotification];

    }else{
     //没开启,请求开启
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]];

    }

2. 添加本地推送私有方法

#pragma mark - 添加本地通知
- (void)addLocalNotification{

    //初始化对象
    UILocalNotification *notification = [[UILocalNotification alloc]init];
    //设置时间
        //时区
    notification.timeZone = [NSTimeZone defaultTimeZone];
    notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
    //重复次数
    notification.repeatInterval = 2;
    notification.repeatInterval = NSCalendarUnitDay;
    //推送内容
    notification.alertBody = @"hello, everyone";
    notification.alertAction = @"I'm Kevin";
    //右上角显示个数
    notification.applicationIconBadgeNumber++;
    //提示声音
    notification.soundName = UILocalNotificationDefaultSoundName;
    //通知参数:
    notification.userInfo = @{@"id":@1, @"user":@"Kevin"};
    //注册
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];

}

3.处理通知

#pragma mark - 进入前台后设置消息信息
- (void)applicationWillEnterForeground:(UIApplication *)application {

    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}


#pragma mark - 调用过用户注册通知方法之后执行
//这个是在App delegate中的代理 方法回调 
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{

    if (notificationSettings.types != UIUserNotificationTypeNone) {

        [self addLocalNotification];
    }


}

4.移除通知

#pragma mark - 移除本地通知
- (void)removeNotification{

    [[UIApplication sharedApplication] cancelAllLocalNotifications];

}

效果演示:![](https://img-blog.csdn.net/20151118224539300)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值