美文网首页
iOS 添加本地推送

iOS 添加本地推送

作者: ShanJiJi | 来源:发表于2016-06-17 15:14 被阅读40次

iOS中的通知推送分为:本地和远程两种。本地推送主要用于日历闹钟等提醒类应用中

1、启动通知
创建一个本地通知:

 //本地通知
    UILocalNotification *localNoti = [[UILocalNotification alloc] init];
    //时区
    localNoti.timeZone = [NSTimeZone defaultTimeZone];
    //触发时间
    localNoti.fireDate = [NSDate dateWithTimeIntervalSinceNow:10.0];
    //重复间隔
    localNoti.repeatInterval = kCFCalendarUnitSecond;
    //通知内容
    localNoti.alertBody = @"欢迎来到英雄联盟";
    //通知声音
    localNoti.soundName = UILocalNotificationDefaultSoundName;
    //通知徽标
    [UIApplication sharedApplication].applicationIconBadgeNumber += 1;
    //通知参数
    localNoti.userInfo = [NSDictionary dictionaryWithObject:@"传递信息内容" forKey:@"通知的Key"];
    //发送通知:
    [[UIApplication sharedApplication] scheduleLocalNotification:localNoti];

2、想要通知有效,需要在 application: didFinishLaunchingWithOptions:里注册通知:

//注册通知:
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {

        UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;

        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];

        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }

3、收到通知后的处理可以写在方法 application:(UIApplication *)application didReceiveLocalNotification: 里面:

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"本地通知" message:[notification.userInfo allValues].firstObject preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cacel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消");
    }];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"确认");
    }];
    [alert addAction:cacel];
    [alert addAction:action];

    [self.window.rootViewController presentViewController:alert animated:YES completion:nil];

4、取消通知
取消一个本地通知

// 获取所有本地通知数组
    NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;

    for (UILocalNotification *notification in localNotifications) {
        NSDictionary *userInfo = notification.userInfo;
        if (userInfo) {
            // 根据设置通知参数时指定的key来获取通知参数
            NSString *info = userInfo[key];

            // 如果找到需要取消的通知,则取消
            if (info != nil) {
                [[UIApplication sharedApplication] cancelLocalNotification:notification];
                //图标的数字清零
                ([UIApplication sharedApplication].applicationIconBadgeNumber >= 1) ?([UIApplication sharedApplication].applicationIconBadgeNumber -= 1):0 ;
                break;
            }
        }
    }

相关文章

网友评论

      本文标题:iOS 添加本地推送

      本文链接:https://www.haomeiwen.com/subject/wzjvdttx.html