APPDelegate需要實(shí)現(xiàn)的代碼為:
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
// 如果應(yīng)用程序在前臺(tái)舰褪,將應(yīng)用程序圖標(biāo)上紅色徽標(biāo)中數(shù)字設(shè)為0
application.applicationIconBadgeNumber = 0;
// 使用UIAlertView顯示本地通知的信息
[[[UIAlertView alloc] initWithTitle:@"收到通知"
message:notification.alertBody
delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil] show];
}
控制器需要實(shí)現(xiàn)的代碼為:
編輯一個(gè)UIApplication *app;對(duì)象 并且初始化
app = [UIApplication sharedApplication];
設(shè)置一個(gè)按鈕實(shí)現(xiàn)以下代碼
- (IBAction)KaiGuan:(id)sender
{
UISwitch * swich = (UISwitch *)sender;
if(swich.on)
{
if([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)])
{
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
//創(chuàng)建一個(gè)本地通知
UILocalNotification * notification = [[UILocalNotification alloc]init];
//設(shè)置一個(gè)通知觸發(fā)時(shí)間
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
//設(shè)置一個(gè)通知時(shí)區(qū)
notification.timeZone = [NSTimeZone defaultTimeZone];
// 設(shè)置通知的重復(fù)發(fā)送的事件間隔
notification.repeatInterval = kCFCalendarUnitHour;
// 設(shè)置通知的聲音
notification.soundName = @"gu.mp3";
//通知標(biāo)題
notification.alertTitle=@"本地通知";
// 設(shè)置當(dāng)設(shè)備處于鎖屏狀態(tài)時(shí)捅儒,顯示通知的警告框下方的title
notification.alertAction = @"打開";
// 設(shè)置通知是否可顯示Action
notification.hasAction = YES;
// 設(shè)置通過通知加載應(yīng)用時(shí)顯示的圖片
notification.alertLaunchImage = @"logo.png";
// 設(shè)置通知內(nèi)容
notification.alertBody = @"本地推送通知";
// 設(shè)置顯示在應(yīng)用程序上紅色徽標(biāo)中的數(shù)字
notification.applicationIconBadgeNumber = 1;
// 設(shè)置userinfo痢虹,用于攜帶額外的附加信息喘漏。
NSDictionary *info = @{@"bys": @"key"};
notification.userInfo = info;
// 調(diào)度通知
[app scheduleLocalNotification:notification];? // ①
}
else
{
NSArray * localArray = [app scheduledLocalNotifications];
if(localArray)
{
for (UILocalNotification * noti in localArray)
{
NSDictionary * dic = noti.userInfo;
if(dic)
{
NSString * inkey = [dic objectForKey:@"key"];
if([inkey isEqualToString:@"bys"])
{
[app cancelLocalNotification:noti];
}
}
}
}
}
}