当前位置:编程学习 > wap >>

iOS学习笔记32—本地通知UILocalNotification

[cpp]
UILocalNotification *notification = [[UILocalNotification alloc] init]; 
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
    [formatter setDateFormat:@"HH:mm:ss"]; 
    //触发通知的时间 
    NSDate *now = [formatter dateFromString:@"15:00:00"]; 
    notification.fireDate = now; 
    //时区 
    notification.timeZone = [NSTimeZone defaultTimeZone]; 
    //通知重复提示的单位,可以是天、周、月 
    notification.repeatInterval = NSDayCalendarUnit; 
    //通知内容 
    notification.alertBody = @"这是一个新的通知"; 
    //通知被触发时播放的声音 
    notification.soundName = UILocalNotificationDefaultSoundName; 
    //执行通知注册 
    [[UIApplication sharedApplication] scheduleLocalNotification:notification]; 

以上代码实现了这么一个场景:一些Todo和闹钟类应用都有通知用户的功能,使用的就是iOS中的本地通知UILocalNotification,还有些应用会在每天、每周、每月固定时间提示用户回到应用看看,也是用的本地通知,以上代码片段就是实现了在每天的下午3点弹出通知提示。

 


如果要在通知中携带参数信息,可以使用下面的方式:


[cpp]
NSDictionary *dic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"]; 
    notification.userInfo = dic; 

如果软件是在运行中,则可以通过AppDelegate中的回调方法获取并处理参数信息:


[cpp]
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification 

    if (notification) { 
        NSDictionary *userInfo =  notification.userInfo; 
        NSString *obj = [userInfo objectForKey:@"key"]; 
        NSLog(@"%@",obj); 
    } 

另外,可以通过两种方式取消注册的本地通知,一种是取消指定的通知,第二种是取消所有的注册通知:


[cpp]
[[UIApplication sharedApplication] cancelLocalNotification:localNotification]; 
   [[UIApplication sharedApplication] cancelAllLocalNotification]; 

以上就简要介绍了一下UILocalNotification的使用,欢迎大家指正和补充!

 

补充:移动开发 , IOS ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,