AppDelegate.m中的代碼
// AppDelegate.m中 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // 處理iOS8本地推送不能收到的問題 float sysVersion=[[UIDevice currentDevice]systemVersion].floatValue; if (sysVersion>=8.0) { UIUserNotificationType type=UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound; UIUserNotificationSettings *setting=[UIUserNotificationSettings settingsForTypes:type categories:nil]; [[UIApplication sharedApplication]registerUserNotificationSettings:setting]; } return YES; }
// 接收本地推送(AppDelegate.m中添加) - (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; }
- (void)applicationWillEnterForeground:(UIApplication *)application { // 直接打開app時,圖標上的數字清零 application.applicationIconBadgeNumber = 0; }
在調用的類中添加的代碼
// 進行推送的方法 // 設置本地推送參數,並進行推送 - (void)scheduleNotification{ UILocalNotification *notification = [[UILocalNotification alloc] init]; //設置5秒之後 NSDate *pushDate = [NSDate dateWithTimeIntervalSinceNow:5]; if (notification != nil) { // 設置推送時間(5秒後) notification.fireDate = pushDate; // 設置時區(此為默認時區) notification.timeZone = [NSTimeZone defaultTimeZone]; // 設置重復間隔(默認0,不重復推送) notification.repeatInterval = 0; // 推送聲音(系統默認) 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]; [app scheduleLocalNotification:notification]; } }