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];

}

iOS开发:本地通知(推送)_第1张图片

你可能感兴趣的:(iOS,开发,iOS,开发之路)