首页 > 代码库 > iOS本地通知

iOS本地通知

为游戏添加了本地推送功能,写下来作为记录

本地通知相对于远程推送来说较简单。

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本地通知