本地通知 ios

来源:互联网 发布:java 获取泛型 gson 编辑:程序博客网 时间:2024/04/28 05:52

//添加本地通知

//在对应viewcontroller 里 添加本地通知

  UILocalNotification *notification=[[UILocalNotification alloc] init];
if (notification!=nil)
  {
NSDate *now = [NSDate date];
notification.fireDate=[now dateByAddingTimeInterval:10];// 设置提醒时间

notification.timeZone=[NSTimeZone defaultTimeZone];// 设置时区,本地时区

notification.repeatInterval = kCFCalendarUnitHour;//循环周期

notification.alertBody=@"有内容更新 请查看!";// 设置消息内容
notification.soundName= UILocalNotificationDefaultSoundName;// 提示音
notification.alertAction=NSLocalizedString(@"锁屏提示文字", nil);// 锁屏后提示文字,不设的话默认为alertBody
notification.applicationIconBadgeNumber = [[[UIApplication sharedApplication] scheduledLocalNotifications] count]+1;//appIcon右上角数字
NSDictionary*info = [NSDictionary dictionaryWithObject:@"test" forKey:@"LocalNotname"];
notification.userInfo = info;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];//执行通知

}

//取消本地通知

UIApplication *app = [UIApplication sharedApplication];
        NSArray *locaArr = [app scheduledLocalNotifications];
        UILocalNotification *localNot;
        if (locaArr) {
            for (UILocalNotification *noti in locaArr) {
                NSDictionary *dict = noti.userInfo;      
                if (dict) {
                    NSString *inKey = [dict objectForKey:@"LocalNotname"];
                    if ([inKey isEqualToString:@"test"]) {
                        if (localNot){
                            localNot = nil;
                        }
//                        break;
                    }
                }
            }
            if (!localNot) {
                localNot = [[UILocalNotification alloc] init];  // lazy
            }
            if (localNot) {
                [app cancelLocalNotification:localNot];//取消推送
            }
        }



//appdelegata里接受通知

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

  // 进入应用时清空appIcon角上数字和重复发送的通知
application.applicationIconBadgeNumber = 0;
[[UIApplication sharedApplication] cancelAllLocalNotifications];

  
  return YES;

}

//接收本地推送
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    NSLog(@"%@",notification.alertBody);
    UILabel *label = [[UILabel alloc]init];
    label.frame = CGRectMake(0, 5, fDeviceWidth, 35);
    label.layer.cornerRadius = 10;
    label.backgroundColor = [UIColor lightGrayColor];
    label.text = notification.alertBody;
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:13];
    label.textAlignment = NSTextAlignmentCenter;
    [self.window addSubview:label];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [label removeFromSuperview];
    });                 //显示2秒后消失
}


(关于远程推送 ,很多成熟的第三方可以直接使用,极光推送/百度云推之类的)

0 0
原创粉丝点击