標籤:style blog io ar color os sp for 檔案
為遊戲添加了本地推送功能,寫下來作為記錄
本地通知相對於遠程推送來說較簡單。
IOS:
添加本地推送
/* name:通知的唯一名字,可作為通知的id來用 message:通知的內容 time:觸發通知的時候(倒計時時間) */void SDKHelper::addLocalNotication(std::string name, std::string message,int time){ UILocalNotification *localNotification = [[UILocalNotification alloc] init]; if (localNotification == nil) { return; } //先把同名的系統通知取消(避免週期性通知) cancleLocalNotication(name); //設定本地通知的觸發時間(如果要立即觸發,無需設定),如20秒後觸發 localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:time]; //通知的重複類型 localNotification.repeatInterval = NSCalendarUnitDay; //設定本地通知的時區 localNotification.timeZone = [NSTimeZone defaultTimeZone]; //設定通知的內容 localNotification.alertBody = [NSString stringWithUTF8String:message.c_str()]; //設定通知動作按鈕的標題 localNotification.alertAction = @"OK"; //設定提醒的聲音,可以自己添加音效檔,這裡設定為預設提示聲 localNotification.soundName = UILocalNotificationDefaultSoundName; //設定通知的相關資訊,這個很重要,可以添加一些標記性內容,方便以後區分和擷取通知的資訊 NSString* pushName = [NSString stringWithFormat:@"%s",name.c_str()]; NSDictionary *infoDic = [NSDictionary dictionaryWithObjectsAndKeys:pushName,@"id",[NSNumber numberWithInteger:345635342],@"time",[NSNumber numberWithInteger:345635342],@"affair.aid", nil]; localNotification.userInfo = infoDic; //在規定的日期觸發通知 [[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; [localNotification release]; }void SDKHelper::cancleLocalNotication(std::string name){ //拿到 存有 所有 推送的數組 NSArray * array = [[UIApplication sharedApplication] scheduledLocalNotifications]; //便利這個數組 根據 key 拿到我們想要的 UILocalNotification for (UILocalNotification * loc in array) { if ([[loc.userInfo objectForKey:@"id"] isEqualToString:[NSString stringWithFormat: @"%s",name.c_str()]]) { //取消 本地推送 [[UIApplication sharedApplication] cancelLocalNotification:loc]; } }}
在通知觸發時,如果應用在前台運行,則會觸發這個方法,如果應用在後台,點擊通知後會觸發,
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification*)notification{ NSLog(@"Application did receive local notifications"); // 取消某個特定的本地通知 for (UILocalNotification *noti in [[UIApplication sharedApplication] scheduledLocalNotifications]) { NSString *notiID = noti.userInfo[@"id"]; NSString *receiveNotiID = notification.userInfo[@"id"]; if ([notiID isEqualToString:receiveNotiID]) { [[UIApplication sharedApplication] cancelLocalNotification:notification]; return; } } application.applicationIconBadgeNumber = 0;}
其中notification.userInfo為自訂的內容
iOS本地通知