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)

阅读更多
版权声明:转载请注明出处:http://blog.csdn.net/kevindongkun https://blog.csdn.net/Kevindongkun/article/details/49914233
文章标签: 数据
个人分类: iOS 开发
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭