ios应用App如果在后台执行,ios系统允许它在受限的时间内运行,从而给App推送本地通知。
1、本地通知介绍:
local notification,用于基于时间行为的通知,比如有关日历或者todo列表的小应用。另外,应用如果在后台执行,ios允许它在受限的时间内运行。比如,一个应用,在后台运行,向应用的服务器端获取消息,当消息到达时,比如下载更新版本的提示消息,通过本地通知机制通知用户。本地通知是UILocalNotification的实例,主要有三类属性:
1、scheduled time,时间周期,用来指定iOS系统发送通知的日期和时间;
2、notification type,通知类型,包括警告信息、动作按钮的标题、应用图标上的badge(数字标记)和播放的声音;
3、自定义数据,本地通知可以包含一个dictionary类型的本地数据。
4、对本地通知的数量限制,ios最多允许最近本地通知数量是64个,超过限制的本地通知将被ios忽略。
2、实际运用,写个定时App,代码实现如下:
/*启动应用后,就发出一个定时通知。这时如果按Home键退出,过10秒后就会启动通知*/
- (void)setLocalNotification
{
UILocalNotification *notification=[[[UILocalNotification alloc] init] autorelease];
if (notification!=nil)
{
NSLog(@">>支持本地通知!");
NSDate *now = [NSDate new];
notification.fireDate = [now dateByAddingTimeInterval:5]; // addTimeInterval ios4.0以下版本
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.alertBody = @"该去吃晚饭了!";
notification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
}
至此,简单的本地通知已经介绍完毕,效果图如下:
3、复杂的本地通知,代码实现如下:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// 首先取消通知次数
application.applicationIconBadgeNumber = 0;
return YES;
}
<pre name="code" class="cpp">// 本地通知实现
- (void)clickSwt:(id)sender
{
UISwitch *swt = (UISwitch *)sender;
int tag = swt.tag - 200;
if (swt.on)
{
UILocalNotification *notification = [[[UILocalNotification alloc] init] autorelease];
NSDate *now = [NSDate date];
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.repeatInterval = 0;
notification.alertAction = @"显示";
notification.soundName = UILocalNotificationDefaultSoundName;
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d",tag], @"key1", nil];
[notification setUserInfo:dict];
switch (tag)
{
case 0:
{
notification.fireDate=[now dateByAddingTimeInterval:5];
notification.applicationIconBadgeNumber = 1;
notification.alertBody = @"通知一";
}
break;
case 1:
{
notification.fireDate=[now dateByAddingTimeInterval:6];
notification.applicationIconBadgeNumber = 2;
notification.alertBody = @"通知二";
}
break;
case 2:
{
notification.fireDate=[now dateByAddingTimeInterval:7];
notification.applicationIconBadgeNumber = 3;
notification.alertBody = @"通知三";
}
break;
default:
break;
}
[[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] == tag)
{
[[UIApplication sharedApplication] cancelLocalNotification:myUILocalNotification];
}
}
}
}
至此,复杂的本地通知已经介绍完毕,效果如下: