第一步:创建本地推送
本地通知
UILocalNotification
// 创建⼀一个本地推送 UILocalNotification * notification = [[UILocalNotification alloc] init];
//设置10秒之后
NSDate *pushDate = [NSDate
dateWithTimeIntervalSinceNow:10];
if (notification != nil) { // 设置推送时间
notification.fireDate = pushDate; // 设置时区
notification.timeZone = [NSTimeZone
defaultTimeZone];
// 设置重复间隔
notification.repeatInterval = kCFCalendarUnitDay;
// 推送声⾳音
notification.soundName = UILocalNotificationDefaultSoundName;
// 推送内容
notification.alertBody = @"推送内容";
// 显⽰示在icon上的红⾊色圈中的数⼦子 notification.applicationIconBadgeNumber = 1; // 设置userinfo ⽅方便在之后需要撤销的时候使⽤用 NSDictionary *info = [NSDictionary
dictionaryWithObject:@"name"forKey:@"key"]; notification.userInfo = info;
//添加推送到UIApplication
UIApplication *app = [UIApplication
sharedApplication];
//对通知进⾏行设置 UIUserNotificationSettings *setting =
[UIUserNotificationSettings settingsForTypes:
(UIUserNotificationTypeBadge|
UIUserNotificationTypeAlert|
UIUserNotificationTypeSound) categories:nil];
[app registerUserNotificationSettings:setting]; [app scheduleLocalNotification:notification]; �
}
第二步:接收本地推送
- (void)applicationDidBecomeActive:(UIApplication
*)application {
//当程序还在后台运⾏行
application.applicationIconBadgeNumber = 0; }
//接收本地推送
- (void)application:(UIApplication *)application didReceiveLocalNotification: (UILocalNotification*)notification{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"本地通知" message:notification.alertBody delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert show];
// 图标上的数字减1 application.applicationIconBadgeNumber -= 1;
}
第三步:发送即时通知
- (IBAction)start:(id)sender {
UIApplication *app = [UIApplication
sharedApplication]; //即时推送
[app presentLocalNotificationNow:notification];}
第四步:解除本地推送
- (IBAction)stop:(id)sender {
// UIApplication *app = [UIApplication sharedApplication];
// //取消本地推送
// [app cancelLocalNotification:notification];
[self stopNotifacation]; }
//解除本地推送
- (void)stopNotifacation{
// 获得 UIApplication
UIApplication *app = [UIApplication
sharedApplication];
//获取本地推送数组
NSArray *localArray = [app
scheduledLocalNotifications];
if (localArray) {
for (UILocalNotification *notify in localArray)
{
NSString *keyString = [notify.userInfo
objectForKey:@"key"];
if ([keyString isEqualToString:@"name"]) {
[app cancelLocalNotification:notify];
} }
} }
注:本地通知注册在本地,如果不取消的话会留下记录。可以通 过获取本地推送数组看到,执行完register后将会存在数组 中,如果不取消下次开启app的时候之前的还存在。