IOS:UILocalNotification使用

添加本地通知:

首先要判断下版本,ios8后的版本,要取得用户的授权

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    float sysVersion=[[UIDevice currentDevice]systemVersion].floatValue;
    if (sysVersion>=8.0) {
        UIUserNotificationType type=UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound;
        UIUserNotificationSettings *setting=[UIUserNotificationSettings settingsForTypes:type categories:nil];
        [[UIApplication sharedApplication]registerUserNotificationSettings:setting];
    }
    return YES;
}

然后添加本地通知:

-(void)addLocalNotification
{

        //定义本地通知对象
        UILocalNotification *notification=[[UILocalNotification alloc]init];
        //设置调用时间
        notification.fireDate=[NSDate dateWithTimeIntervalSinceNow:5.0];//通知触发的时间,10s以后
        notification.repeatInterval=2;//通知重复次数
        //notification.repeatCalendar=[NSCalendar currentCalendar];//当前日历,使用前最好设置时区等信息以便能够自动同步时间

        //设置通知属性
        notification.alertBody=@"最近添加了诸多有趣的特性,是否立即体验?"; //通知主体
        notification.applicationIconBadgeNumber=1;//应用程序图标右上角显示的消息数
        notification.alertAction=@"打开应用"; //待机界面的滑动动作提示
        notification.alertLaunchImage=@"Default";//通过点击通知打开应用时的启动图片,这里使用程序启动图片
        //notification.soundName=UILocalNotificationDefaultSoundName;//收到通知时播放的声音,默认消息声音
        notification.soundName=@"msg.caf";//通知声音(需要真机才能听到声音)
    //设置用户信息
        notification.userInfo=@{@"id":@1,@"user":@"Kenshin Cui"};//绑定到通知上的其他附加信息

        //调用通知
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

接收消息:

#pragma mark 进入程序后收到消息信息后的操作

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    NSLog(@"前台收到通知");
    UIApplicationState state = application.applicationState;
    if (state == UIApplicationStateActive) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"时间提醒"
                                                        message:notification.alertBody
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}
#pragma mark 进入从通知栏点击消息通知后的操作
-(void)applicationWillEnterForeground:(UIApplication *)application{
    [[UIApplication sharedApplication]setApplicationIconBadgeNumber:0];//进入前台取消应用消息图标

}

取消通知:

#pragma mark 移除本地通知,在不需要此通知时记得移除
-(void)removeNotification{
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
}

你可能感兴趣的:(ios)