说到推送,项目开发中有可能会使用定时推送.类似闹钟,或者提醒事项,定个时间发起推送.
使用本地推送和普通推送一样,也需要注册推送通知.
在Appdelegate.m中的
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
方法中填写下放代码.
if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
然后实现接受本地推送的方法
//接受处理本地推送
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification NS_AVAILABLE_IOS(4_0) {
//使用UIAlertView显示推送的消息
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:notification.alertTitle message:notification.alertBody delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alert show];
}
好了,先在我们创建一个定时推送.
- (void)setUpLocalNotification:(NSString *)dateStr {
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
if (localNotification == nil) {
return;
}
//处理时间字符串
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm";
NSDate *fireDate = [formatter dateFromString:dateStr];
NSAssert(fireDate, @"dateStr类型不匹配,或者为nil");
//设置UILocalNotification
[localNotification setTimeZone:[NSTimeZone defaultTimeZone]];//设置时区
localNotification.fireDate = fireDate;//设置触发时间
localNotification.repeatInterval = 0;//设置重复间隔
localNotification.alertBody = @"定时推送的信息";
localNotification.alertTitle = @"定时推送";
localNotification.soundName = UILocalNotificationDefaultSoundName;
//当然你也可以调取当前的气泡,并且设置.也可以设置一个userInfo进行传递信息
/*
[localNotification setApplicationIconBadgeNumber:66];
localNotification.applicationIconBadgeNumber += 1;
localNotification.userInfo = @{@"KEY" : @"VALUE"};
*/
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
然后给定你的dateStr,就行了
注意的是:dateStr的类型需要和你的dateFormat类型相同,不然fireDate会为nil.