app在后台本地通知 ios
2016-08-29 23:15:12 BianHuanShiZhe 阅读数 276

UILocalNotification常用属性

 

 fireDate;          通知的触发时间

 timeZone;          通知所在时区,如果指定时区,可以自行调整时间

 alertBody;         通知的正文

 soundName;         通知播放的声音,如果用UILocalNotificationDefaultSoundName,使用系统默认声音

 applicationIconBadgeNumber; 应用程序图标

 userInfo;          数据字典



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

{

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings
                                                                             settingsForTypes:(UIUserNotificationTypeSound |UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
                                                                             categories:nil]];
        
        
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    else
    {
        //ios7注册推送通知
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
    }


    // 截获本地通知,用户通过通知的横幅点击进入系统,字典中才能找到本地通知

    UILocalNotification *notification = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];

    

    // 判断通知是否存在

    if (notification) {

        NSLog(@"%@", notification.userInfo);

        [notification.userInfo writeToFile:@"/users/apple/Desktop/123.plist" atomically:YES];

    }

    

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    self.window.backgroundColor = [UIColor whiteColor];

    

    

    [self.window makeKeyAndVisible];

    return YES;

}


#pragma mark - 进入前台,清除右上角图标

- (void)applicationWillEnterForeground:(UIApplication *)application

{

    [application setApplicationIconBadgeNumber:0];

}


#pragma mark - 进入后台

- (void)applicationDidEnterBackground:(UIApplication *)application

{

    [self loadNotification];

}


#pragma mark - 创建本地通知

- (void)loadNotification

{

    UILocalNotification *notification = [[UILocalNotification alloc]init];

    // 5秒钟之后触发

    notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];

    notification.alertBody = @"出大事了";

    notification.soundName = UILocalNotificationDefaultSoundName;

    notification.applicationIconBadgeNumber = 100;

    

    notification.userInfo = @{@"userName": @"马大哈", @"age": @(18)};

    

    // 要调用本地通知,需要通过UIApplication来统一调度

    [[UIApplication sharedApplication]scheduleLocalNotification:notification];

}

2015-11-27 23:29:00 u012317018 阅读数 295

本地通知实现步骤:

1> 在didFinishLaunchingWithOptions 提前注册通知类型 (iOS8以上就需要)

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

    UIUserNotificationType type = UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound;

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

    return YES;
}

2> 创建本地通知–>设置通知其他属性 –> 注册通知

 //创建本地通知
    UILocalNotification *note = [[UILocalNotification alloc]init];
    //设置属性
    note.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
    note.timeZone = [NSTimeZone defaultTimeZone];
    note.applicationIconBadgeNumber = 888;
    note.alertAction = @"这锁屏界面消息";
    note.alertBody = @"通知内容";

    //注册通知
    UIApplication *application =[UIApplication sharedApplication];
    [application scheduleLocalNotification:note];
2017-06-16 16:07:00 weixin_34261415 阅读数 16

gitHub地址:https://github.com/pengjinguang521/localNotification.git

demo中对本地通知进行了详细封装,并且适配iOS10。在手机挂起、退出、前台 三种状态都有处理。封装后的api调用也相对简单,使用方法如下:

3150942-e8a6ad71d1d02a2b.png
封装的文件夹

1、将上图中的LocalNotification文件夹拖入你的项目中。

2、一句代码添加通知:

3150942-1d6402c4e832244f.png
添加通知的方法

3、接收到本地通知的处理方法:

3150942-90f641b301b1afb2.png
处理收到通知的方法


至于具体实现过程,可以下载代码,自己查看,不懂得和写的不好不对的地方欢迎来咨询指证。  简化开发过程,我们精益求精。

2012-01-05 16:15:25 chiefoforc 阅读数 274

RT:http://www.cocoachina.com/newbie/tutorial/2012/0104/3827.html



本地通知 

本地通知,local notification,用于基于时间行为的通知,比如有关日历或者todo列表的小应用。另外,应用如果在后台执行,iOS允许它在受限的时间内运行,它也会发现本地通知有用。比如,一个应用,在后台运行,向应用的服务器端获取消息,当消息到达时,比如下载更新版本的提示消息,通过本地通知机制通知用户。

本地通知是UILocalNotification的实例,主要有三类属性:

  • scheduled time,时间周期,用来指定iOS系统发送通知的日期和时间;
  • notification type,通知类型,包括警告信息、动作按钮的标题、应用图标上的badge(数字标记)和播放的声音;
  • 自定义数据,本地通知可以包含一个dictionary类型的本地数据。

对本地通知的数量限制,iOS最多允许最近本地通知数量是64个,超过限制的本地通知将被iOS忽略。

如果就写个简单的定时提醒,是很简单的,比如这样:

示例写的很简单,启动应用后,就发出一个定时通知,10秒后启动。这时按Home键退出,一会儿就会提示上图的提示信息。如果应用不退出则无效。

代码如下:

UILocalNotification *notification=[[UILocalNotification alloc] init]; 
if (notification!=nil) { 
    NSLog(@">> support local notification"); 
    NSDate *now=[NSDate new]; 
    notification.fireDate=[now addTimeInterval:10]; 
    notification.timeZone=[NSTimeZone defaultTimeZone]; 
    notification.alertBody=@"该去吃晚饭了!"; 
    [[UIApplication sharedApplication]   scheduleLocalNotification:notification];

 

更详细的代码见官方文档:《Scheduling, Registering, and Handling Notifications》,可以设置比如声音,比如用户定义数据等。

设置更多本地通知的信息:

 

  • 设置icon上数字。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    // Override point for customization after application launch. 
    ///////////// 
  application.applicationIconBadgeNumber = 0; 
    // Add the view controller’s view to the window and display. 
    [self.window addSubview:viewController.view]; 
    [self.window makeKeyAndVisible];

    return YES; 
}

  • 添加通知时间,通知类型,取消通知

#pragma mark – 
#pragma mark onChageValue 
-(IBAction)onChangeValue:(id)sender 

    UISwitch *switch1=(UISwitch *)sender; 
    if (switch1.on) { 
        UILocalNotification *notification=[[UILocalNotification alloc] init]; 
        NSDate *now1=[NSDate date];  
        notification.timeZone=[NSTimeZone defaultTimeZone]; 
        notification.repeatInterval=NSDayCalendarUnit; 
        notification.applicationIconBadgeNumber = 1; 
        notification.alertAction = NSLocalizedString(@"显示", nil); 
        switch (switch1.tag) { 
            case 0: 
            { 
                notification.fireDate=[now1 dateByAddingTimeInterval:10]; 
                notification.alertBody=self.myLable1.text; 
            } 
                break; 
            case 1: 
            { 
                notification.fireDate=[now1 dateByAddingTimeInterval:20]; 
                notification.alertBody=self.myLable2.text; 
            } 
                break; 
            case 2: 
            { 
                notification.fireDate=[now1 dateByAddingTimeInterval:30]; 
                notification.alertBody=self.myLable3.text; 
            } 
                break; 
            default: 
                break; 
        } 
        [notification setSoundName:UILocalNotificationDefaultSoundName]; 
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: 
                              [NSString stringWithFormat:@"%d",switch1.tag], @"key1", nil]; 
        [notification setUserInfo:dict]; 
        [[UIApplication sharedApplication]   scheduleLocalNotification:notification]; 
    }else { 
        NSArray *myArray=[[UIApplication sharedApplication] scheduledLocalNotifications]; 
        for (int i=0; i<[myArray count]; i++) { 
            UILocalNotification    *myUILocalNotification=[myArray objectAtIndex:i]; 
            if ([[[myUILocalNotification userInfo] objectForKey:@"key1"] intValue]==switch1.tag) { 
                [[UIApplication sharedApplication] cancelLocalNotification:myUILocalNotification]; 
            } 
        } 
    } 
}

2016-02-01 16:58:40 cjh16102377 阅读数 207

首先在注册通知

 if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){
        
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
        
    }

再需要使用通知的地方创建通知

-(void)createLocalNotifaction{
    //设置20秒之后
    
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    
    /*
     
     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
     
     [formatter setDateFormat:@"HH:mm:ss"];
     
     NSDate *now = [formatter dateFromString:@"15:00:00"];//触发通知的时间
     
     */
    UILocalNotification *noti = [[UILocalNotification alloc] init];
    
    if (noti) {
        
        //设置推送时间
        
        noti.fireDate = date;//=now
        
        //设置时区
        
        noti.timeZone = [NSTimeZone defaultTimeZone];
        
        //设置重复间隔
        
       // noti.repeatInterval = NSCalendarUnitMinute;
        
        //推送声音
        
        noti.soundName = @"push01.caf";
        
        //内容
        
        noti.alertBody = @"推送内容";
        
        //显示在icon上的红色圈中的数子
        
        noti.applicationIconBadgeNumber = 1;
        
        //设置userinfo 方便在之后需要撤销的时候使用
        
        NSDictionary *infoDic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
        
        noti.userInfo = infoDic;
        
        //添加推送到uiapplication        
        
        UIApplication *app = [UIApplication sharedApplication];
        
        [app scheduleLocalNotification:noti];  
        
    }
}

关闭所有通知

-(void)cancelNotify{
    
    //删除全部的通知
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    
}

关闭指定通知

  
            for (UILocalNotification *noti in [[UIApplication sharedApplication] scheduledLocalNotifications]) {
                
                if([noti.userInfo[@"key"] isEqualToString:@"name"]){
                    
                    [[UIApplication sharedApplication] cancelLocalNotification:noti];
                }
            }

倒计时结束播放音乐

-(void)cutDownCount:(NSTimer *)theTimer{
    
    NSString *strSecond;
    NSString *strMinute;
    if(senconds < 10){
        
        strSecond = [NSString stringWithFormat:@"0%d",(int)senconds];
    }else{
        
        strSecond = [NSString stringWithFormat:@"%d",(int)senconds];
    }
    if(projectTime < 10){
        
        strMinute = [NSString stringWithFormat:@"0%d",(int)projectTime];
    }else{
        
        strMinute = [NSString stringWithFormat:@"%d",(int)projectTime];
    }
    
    NSString *buttonTitle = [NSString stringWithFormat:@"%@:%@",strMinute,strSecond];
    coutTimeLabel.text = buttonTitle;
    if(senconds == 0){
        
        if(projectTime == 0 && senconds == 0){
            
            //计时器结束
            [theTimer invalidate];
            [self showAlertView];
            
            for (UILocalNotification *noti in [[UIApplication sharedApplication] scheduledLocalNotifications]) {
                
                if([noti.userInfo[@"key"] isEqualToString:@"name"]){
                    
                    [[UIApplication sharedApplication] cancelLocalNotification:noti];
                }
            }
//            movePlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"夜空中最亮的星" ofType:@"mp3"]] error:nil];
//            
            NSString *tmp=[[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:@"夜空中最亮的星.mp3"];
            NSLog(@"%@",tmp);
            NSURL *moveMP3=[NSURL fileURLWithPath:[[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:@"夜空中最亮的星.mp3"]];
            NSError *err=nil;
            movePlayer=[[AVAudioPlayer alloc] initWithContentsOfURL:moveMP3 error:&err];
            movePlayer.volume=1.0;
            [movePlayer prepareToPlay];
            if (err!=nil) {
                NSLog(@"move player init error:%@",err);
            }else {
                [movePlayer play];
            }
            projectTime --;
            senconds = 59;
        }
    }
    senconds--;
}


iOS本地通知

阅读数 8

iOS 本地通知

阅读数 17

iOS 本地通知

阅读数 278

IOS 本地通知

阅读数 655

iOS本地通知

阅读数 142

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