iOS本地推送的實現,相容iOS8
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]; }}