第一步:創(chuàng)建本地推送
本地通知
UILocalNotification
// 創(chuàng)建?一個(gè)本地推送 UILocalNotification * notification = [[UILocalNotification alloc] init];
//設(shè)置10秒之后
NSDate *pushDate = [NSDate
dateWithTimeIntervalSinceNow:10];
if (notification != nil) { // 設(shè)置推送時(shí)間
notification.fireDate = pushDate; // 設(shè)置時(shí)區(qū)
notification.timeZone = [NSTimeZone
defaultTimeZone];
// 設(shè)置重復(fù)間隔
notification.repeatInterval = kCFCalendarUnitDay;
// 推送聲?音
notification.soundName = UILocalNotificationDefaultSoundName;
// 推送內(nèi)容
notification.alertBody = @"推送內(nèi)容";
// 顯?示在icon上的紅?色圈中的數(shù)?子 notification.applicationIconBadgeNumber = 1; // 設(shè)置userinfo ?方便在之后需要撤銷(xiāo)的時(shí)候使?用 NSDictionary *info = [NSDictionary
dictionaryWithObject:@"name"forKey:@"key"]; notification.userInfo = info;
//添加推送到UIApplication
UIApplication *app = [UIApplication
sharedApplication];
//對(duì)通知進(jìn)?行設(shè)置 UIUserNotificationSettings *setting =
[UIUserNotificationSettings settingsForTypes:
(UIUserNotificationTypeBadge|
UIUserNotificationTypeAlert|
UIUserNotificationTypeSound) categories:nil];
[app registerUserNotificationSettings:setting]; [app scheduleLocalNotification:notification]; ?
}
第二步:接收本地推送
- (void)applicationDidBecomeActive:(UIApplication
*)application {
//當(dāng)程序還在后臺(tái)運(yùn)?行
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];
// 圖標(biāo)上的數(shù)字減1 application.applicationIconBadgeNumber -= 1;
}
第三步:發(fā)送即時(shí)通知
- (IBAction)start:(id)sender {
UIApplication *app = [UIApplication
sharedApplication]; //即時(shí)推送
[app presentLocalNotificationNow:notification];}
第四步:解除本地推送
- (IBAction)stop:(id)sender {
// UIApplication *app = [UIApplication sharedApplication];
// //取消本地推送
// [app cancelLocalNotification:notification];
[self stopNotifacation]; }
//解除本地推送
- (void)stopNotifacation{
// 獲得 UIApplication
UIApplication *app = [UIApplication
sharedApplication];
//獲取本地推送數(shù)組
NSArray *localArray = [app
scheduledLocalNotifications];
if (localArray) {
for (UILocalNotification *notify in localArray)
{
NSString *keyString = [notify.userInfo
objectForKey:@"key"];
if ([keyString isEqualToString:@"name"]) {
[app cancelLocalNotification:notify];
} }
} }
注:本地通知注冊(cè)在本地,如果不取消的話會(huì)留下記錄嚼沿》侠耄可以通 過(guò)獲取本地推送數(shù)組看到,執(zhí)行完register后將會(huì)存在數(shù)組 中,如果不取消下次開(kāi)啟app的時(shí)候之前的還存在。