不费话,直接上代码,然后解释
Class cls = NSClassFromString(@"UILocalNotification");
if (cls != nil) {
UILocalNotification *notif = [[cls alloc] init];
notif.fireDate = [datePicker date];
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.alertBody = @"Did you forget something?";
notif.alertAction = @"Show me";
notif.soundName = UILocalNotificationDefaultSoundName;
notif.applicationIconBadgeNumber = 1;
NSDictionary *userDict = [NSDictionary dictionaryWithObject:reminderText.text
forKey:kRemindMeNotificationDataKey];
notif.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
[notif release];
}
取消所有已经设置的本地通知
代码兼容,确保本地通知可用。因为本地通知是iOS4以后的故事,所以直接在较早的系统上用的话会崩溃~
if (cls != nil) {
UILocalNotification *notif = [[cls alloc] init];
初始化一个本地通知
设置本地通知的时间和时区.话说,我一直以为fireDate是firstDate呢。
notif.timeZone = [NSTimeZone defaultTimeZone];
控制弹框内容和动作按钮标题
notif.alertAction = @"Show me";
这个alertAction也会影响”划动解锁”,就是锁屏的时候收到本地通知的显示
设置提醒声音
上面是使用系统默认的铃声,你也可以指定一下.
需要注意的sms.caf有时间长度和格式限制
设置程序Icon上的数字
针对本地通知设置一些自定义信息:
forKey:kRemindMeNotificationDataKey];
notif.userInfo = userDict;
就是方便传递一些数据的
计划这个本地通知,并释放。
[notif release];
关于计划通知还一个更酷的功能:立即显示
ok,解释完了,上面这些东西,几乎所以关于本地通知的教程都有,我要说的是下面的。
处理好本地通知:
1.应用未运行的情况
2.应用正在运行。
3.应用运行在后台(挂起或者在执行后台任务)
应用未运行的情况
这时候只要处理好,程序启动时的参数launchOptions就可以了。
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
Class cls = NSClassFromString(@"UILocalNotification");
if (cls) {
UILocalNotification *notification = [launchOptions objectForKey:
UIApplicationLaunchOptionsLocalNotificationKey];
if (notification) {
NSString *reminderText = [notification.userInfo
objectForKey:kRemindMeNotificationDataKey];
[viewController showReminder:reminderText];
}
}
application.applicationIconBadgeNumber = 0;
[window addSubview:viewController.view];
[window makeKeyAndVisible];
return YES;
}
应用运行在后台
这时程序会优先通过本地代理获取这个通知。
didReceiveLocalNotification:(UILocalNotification *)notification {
application.applicationIconBadgeNumber = 0;
NSString *reminderText = [notification.userInfo
objectForKey:kRemindMeNotificationDataKey];
NSLog(@"%@",reminderText);
}
应用运行在后台
应用启动完以后,用户按了一下Home键,应用就被搁到后台运行了。这时当有一个通知,用户点击”View”的时间,你会发现上面一个代理还是会被调用。区别这个通知有没有被用户看到过也很简单,加个应用运行状态判断就好了。
didReceiveLocalNotification:(UILocalNotification *)notification {
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateInactive) {
//这个通知用户已经看过了。
}
that’s all
参考文档:
iPhone开发 UILocalNotification的使用
Adding Local Notifications With iOS 4
转载请注明: 转自Rainbird的个人博客
本文链接: 关于UILocalNotification一些更深刻的认识