iOS本地通知

来源:互联网 发布:网络执法官最新破解版 编辑:程序博客网 时间:2024/06/05 17:38

在需要进行本地通知的地方

/ 初始化本地通知    UILocalNotification *localNotification = [[UILocalNotification alloc]init];        // 设置触发时间    localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:20];        // 设置时区    localNotification.timeZone = [NSTimeZone defaultTimeZone];        // 设置通知重复间隔    localNotification.repeatInterval = kCFCalendarUnitSecond;        // 设置通知内容    localNotification.alertBody = @"本地通知...";        // 设置角标    localNotification.applicationIconBadgeNumber = 1;        // 设置触发通知时的声音    localNotification.soundName = UILocalNotificationDefaultSoundName;        // 设置通知参数    localNotification.userInfo = [NSDictionary dictionaryWithObject:@"测试本地通知" forKey:@"key"];        // ios8之后 需要注册通知    if ([[UIApplication sharedApplication] respondsToSelector:@selector (registerUserNotificationSettings:)]) {        UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];        [[UIApplication sharedApplication]registerUserNotificationSettings:settings];                // 设置重复提示单位        localNotification.repeatInterval = NSCalendarUnitDay;            }        // 注册通知    [[UIApplication sharedApplication]scheduleLocalNotification:localNotification];

在AppDelegate中添加接收方法:

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{        NSString *localNotificationMessage = [notification.userInfo objectForKey:@"key"];    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"本地通知" message:localNotificationMessage delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];        NSLog(@"点击进入需求的App");        [alertView show];        // 更新角标数目,每点击一次减少角标    NSInteger badgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber;    badgeNumber --;    if (badgeNumber >= 0){        badgeNumber = badgeNumber;    }else{        badgeNumber = 0;    }    [UIApplication sharedApplication].applicationIconBadgeNumber = badgeNumber;    }


删除本地通知:

删除指定key通知(本地通知队列):

NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;    for (UILocalNotification *notification in localNotifications){        NSDictionary *userInfo = notification.userInfo;        if (userInfo){            NSString *info = userInfo[key];            if (info != nil){                [[UIApplication sharedApplication]cancelLocalNotification:notification];                break;            }        }    }

删除全部本地通知(本地通知队列):

[[UIApplication sharedApplication]cancelAllLocalNotifications];

运行本地通知后效果如图:



0 0
原创粉丝点击