关闭

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

标签: 数据
177人阅读 评论(0) 收藏 举报
分类:

主要步骤

/*
        创建本地通知的步骤:
     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];

}

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

2
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:91687次
    • 积分:1756
    • 等级:
    • 排名:千里之外
    • 原创:72篇
    • 转载:19篇
    • 译文:0篇
    • 评论:62条