首先在 appdelegate 中添加
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
// 如果應用程序在前臺,將應用程序圖標上紅色徽標中數字設為0
application.applicationIconBadgeNumber = 0;
// 使用UIAlertView顯示本地通知的信息
[[[UIAlertView alloc] initWithTitle:@"收到通知"
message:notification.alertBody
delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil] show];
}
然后在 viewcontroller?
@interface ViewController ()
{
UIApplication * app;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
app = [UIApplication sharedApplication];
}
- (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]];
}
//創建一個本地通知
UILocalNotification * notification = [[UILocalNotification alloc]init];
//設置一個通知觸發時間
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:7];
//設置一個通知時區
notification.timeZone = [NSTimeZone defaultTimeZone];
// 設置通知的重復發送的事件間隔
notification.repeatInterval = kCFCalendarUnitHour;
// 設置通知的聲音
notification.soundName = @"gu.mp3";
//通知標題
notification.alertTitle=@"666666";
// 設置當設備處于鎖屏狀態時,顯示通知的警告框下方的title
notification.alertAction = @"打開";
// 設置通知是否可顯示Action
notification.hasAction = YES;
// 設置通過通知加載應用時顯示的圖片
notification.alertLaunchImage = @"0.jpg";
// 設置通知內容
notification.alertBody = @"six six six? !";
// 設置顯示在應用程序上紅色徽標中的數字
notification.applicationIconBadgeNumber = 1;
// 設置userinfo,用于攜帶額外的附加信息。
NSDictionary *info = @{@"bys": @"key"};
notification.userInfo = info;
// 調度通知
[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];
}
}
}
}
}
}
@end