IOS 本地通知推送消息

在现在的移动设备中,好多应用性的APP都用到了推送服务,但是有好多推送的内容,比如有的只是单纯的进行推送一个闹钟类型的,起了提醒作
用,有的则是推送的实质性的内容,这就分为推送的内容来区别用什么推送,现有的推送有 极光推送 , 友盟推送 , 个推 , 百度推送 , APNS 的苹果服务器推 送,目前我所了解的有这几种,可能还有很多的推送sdk ,我还没接触过,不过我所接触过的码神和我这样的码农,我所了解他们使用的极光推送居多,下面来说下推送流程 ,我只说我对 推送的理解和我项目中所用到的推送的我的具体做法。。

第一种 单纯的推送提醒功能,不做什么特定的推送服务

推送的步骤如下

  1. 创建 UILocationNotification

  2. 设置处理通知的时间fireDate

  3. 配置通知的内容:通知主体、通知声音、图标文字等

  4. 配置通知传递的自定义数据(可选)

  5. 调用通知
    如果项目中单纯用的推送是为了提醒作用完全可以只用一个通知来处理就可以,注册通知的方法需要在appdelegate 里面进行设置,具体代码如下

当你确定要点击使用通知的时候的代码如下

- (void)viewDidLoad {
  [super viewDidLoad];
  NSString * path=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
  NSLog(@"%@",path);
  NSURL * url=[NSURL URLWithString:@"http://localhost/logo.php?userName=jereh&pwd=123"];
  NSMutableURLRequest * request=[NSMutableURLRequest requestWithURL:url];
  request.cachePolicy=NSURLRequestReturnCacheDataElseLoad;
  NSOperationQueue *mainQueue=[NSOperationQueue mainQueue];
  NSURLCache * catche=[NSURLCache sharedURLCache];
  [catche removeCachedResponseForRequest:request];
  [catche removeAllCachedResponses];
  NSCachedURLResponse * res= [catche cachedResponseForRequest:request];  
  NSLog(@"===%d",res==nil);
  [NSURLConnection sendAsynchronousRequest:request queue:mainQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
  }];
}
//注册通知,点击按钮进行通知的时候调用
- (IBAction)setAlert:(id)sender {
  UIApplication * application=[UIApplication sharedApplication];
  //如果当前应用程序没有注册本地通知,需要注册
  if([application currentUserNotificationSettings].types==UIUserNotificationTypeNone){
    //设置提示支持的提示方式
//      UIUserNotificationTypeBadge   提示图标
//      UIUserNotificationTypeSound   提示声音
//      UIUserNotificationTypeAlert   提示弹框
    UIUserNotificationSettings * setting=[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
    [application registerUserNotificationSettings:setting];
  }
  //删除之前的重复通知
  [application cancelAllLocalNotifications];
  //添加本地通知
  NSDate * date=[NSDate dateWithTimeIntervalSinceNow:10];
[ self LocalNotificationSleep :date];

}

要注意这里,在不使用通知的时候记得要把通知删除,不然什么时候他都会给你发送通知

#pragma mark - 添加本地通知
- (void) LocalNotificationSleep:(NSDate *) date{
  UILocalNotification * noti=[[UILocalNotification alloc] init];
  //设置开始时间
  noti.fireDate=date;
  //设置body
  noti.alertBody=@"你有一条消息提醒,请查收!";
  //设置action
  noti.alertAction=@"详情";
  //设置闹铃
  noti.soundName=@"4195.mp3";
#warning 注册完之后如果不删除,下次会继续存在,即使从模拟器卸载掉也会保留
  //注册通知
  [[UIApplication sharedApplication] scheduleLocalNotification:noti];
}

第二种推送 极光推送 所用到的sdk

下载地址: http://docs.jpush.io/resources/

JPushHelper .h 文件夹里面代码

#import <Foundation/Foundation.h>

#import <UIKit/UIKit.h>


//激光推送
@interface JPushHelper : NSObject


// 在应用启动的时候调用
+ (void)setupWithOptions:(NSDictionary *)launchOptions;

// 在appdelegate注册设备处调用
+ (void)registerDeviceToken:(NSData *)deviceToken;

// ios7以后,才有completion,否则传nil
+ (void)handleRemoteNotification:(NSDictionary *)userInfo completion:(void (^)(UIBackgroundFetchResult))completion;

// 显示本地通知在最前面
+ (void)showLocalNotificationAtFront:(UILocalNotification *)notification;

//设置JPush服务器的badge的值
+ (BOOL)setBadge:(NSInteger)value;

//清除JPush服务器对badge值的设定
+ (void)resetBadge;

//setDebugMode获取更多的Log信息
//开发过程中建议开启DebugMode
+ (void)setDebugMode;

//setLogOFF关闭除了错误信息外的所有Log
//发布时建议开启LogOFF用于节省性能开销
+ (void)setLogOFF;
@end

JPushHelper.m 代码

#import "JPushHelper.h"
@implementation JPushHelper
// 在应用启动的时候调用---ok
+ (void)setupWithOptions:(NSDictionary *)launchOptions {
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
  // ios8之后可以自定义category
  if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
    // 可以添加自定义categories
    [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                             UIUserNotificationTypeSound |
                             UIUserNotificationTypeAlert)
                       categories:nil];
  } else {
  // ios8之前 categories 必须为nil
  [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                             UIRemoteNotificationTypeSound |
                             UIRemoteNotificationTypeAlert)
                       categories:nil];
  }
#else
  // categories 必须为nil
  [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                           UIRemoteNotificationTypeSound |
                           UIRemoteNotificationTypeAlert)
                     categories:nil];
#endif
  // Required
  [APService setupWithOption:launchOptions];  
  return;
}
// 在appdelegate注册设备处调用---ok
+ (void)registerDeviceToken:(NSData *)deviceToken {
  [APService registerDeviceToken:deviceToken];
  return;
}
// ios7以后,才有completion,否则传nil--------引用同一个方法,区别completion
+ (void)handleRemoteNotification:(NSDictionary *)userInfo completion:(void (^)(UIBackgroundFetchResult))completion {
  [APService handleRemoteNotification:userInfo];
  if (completion) {
    completion(UIBackgroundFetchResultNewData);
  }
  return;
}
// 显示本地通知在最前面
+ (void)showLocalNotificationAtFront:(UILocalNotification *)notification {
//  notification 当前触发的UILocalNotification
//  notificationKey 过滤不需要前台显示的通知。只有notificationKey标示符的通知才会在前台显示。如果需要全部都显示,该参数传nil。
  [APService showLocalNotificationAtFront:notification identifierKey:nil];
  return;
}
//设置JPush服务器的badge的值
+ (BOOL)setBadge:(NSInteger)value
{
  [APService setBadge:value];
  return YES;
}
//清除JPush服务器对badge值的设定
+ (void)resetBadge
{
  [APService resetBadge];
}
//setDebugMode获取更多的Log信息
//开发过程中建议开启DebugMode
+ (void)setDebugMode
{
  [APService setDebugMode];
}
//setLogOFF关闭除了错误信息外的所有Log
//发布时建议开启LogOFF用于节省性能开销
+ (void)setLogOFF
{
  [APService setLogOFF];
}
@end
在AppDelegate.m里面的      didFinishLaunchingWithOptions   进行填写

//   激光推送------第一步
    [JPushHelper setupWithOptions:launchOptions];
    
    //    关闭不必要打印
    [JPushHelper setLogOFF];
#pragma mark - 激光推送
//激光推送---在此接收设备令牌
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
   
    
    //   激光推送------第二步
    [JPushHelper registerDeviceToken:deviceToken];
    
    
    return;
    
    
}
然后在AppDelegate里面的代理方法里面填写极光推送的方法

#pragma mark - 激光推送---------自定义消息的展示
//激光推送---(无论是在前台还是在后台) apn内容为userInfo---------ios7之前---------目前无效,因为直接ios7开始
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
  //   后台
  if (application.applicationState != UIApplicationStateActive) {
    _BadgeNumber++;
    [JPushHelper setBadge:_BadgeNumber];
    [application setApplicationIconBadgeNumber:_BadgeNumber];
  }
  //   激光推送------第三步
  [JPushHelper handleRemoteNotification:userInfo completion:nil];
  //前台
  if (application.applicationState == UIApplicationStateActive) {
    _BadgeNumber = 0;
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:1];
    //  本地通知有两个版本
    if(iOS8){
      [APService setLocalNotification:date alertBody:[userInfo objectForKey:@"aps"][@"alert"]  badge:-1 alertAction:nil identifierKey:nil userInfo:nil soundName:nil region:nil regionTriggersOnce:YES category:nil];
    }else
    {
      [ APService setLocalNotification:date alertBody:[userInfo objectForKey:@"aps"][@"alert"] badge:-1 alertAction:nil identifierKey:nil userInfo:nil soundName:nil];
    }
    [JPushHelper resetBadge];
  }
  return;
}
//ios7以后
- (void)application:(UIApplication *)application
didReceiveRemoteNotification
           :(NSDictionary *)userInfo
fetchCompletionHandler
           :(void (^)(UIBackgroundFetchResult))
completionHandler
{
  //   后台
  /**
   *  后台通知
   */
  if (application.applicationState != UIApplicationStateActive) {
    _BadgeNumber++;
    [JPushHelper setBadge:_BadgeNumber];
    [application setApplicationIconBadgeNumber:_BadgeNumber];
    [WDLNSNC postNotificationName:@"showJpushMessageToViewController" object:nil userInfo:userInfo];        
  }
  [JPushHelper handleRemoteNotification:userInfo completion:completionHandler];
  //前台
  /**
   *  前台显示信息,这里需要处理一下,判断到底是哪个界面,前台收到通知,alert显示?
   */
  if (application.applicationState == UIApplicationStateActive) {
    _BadgeNumber = 0;
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:1];
    //  本地通知有两个版本
    if(iOS8){
    [APService setLocalNotification:date alertBody:[userInfo objectForKey:@"aps"][@"alert"]  badge:-1 alertAction:@"打开" identifierKey:nil userInfo:nil soundName:nil region:nil regionTriggersOnce:YES category:nil];

    }else
    {
      [ APService setLocalNotification:date alertBody:[userInfo objectForKey:@"aps"][@"alert"] badge:-1 alertAction:@"打开" identifierKey:nil userInfo:nil soundName:nil];
    }
    [JPushHelper resetBadge];
  }
  return;   
}

#pragma mark - 激光推送---本地
//极光推送-----本地通知-----显示本地通知在最前面
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
//  环信通知还是极光推送
  if(![notification.alertBody isEqualToString:@"您有一条新的消息"])
  {   
//  [JPushHelper showLocalNotificationAtFront:notification];
  }
  return;
}

然后还可以自定义推送消息内容

//极光推送
//获取自定义消息
- (void)networkDidReceiveMessage:(NSNotification *)notification {
  //    NSDictionary * userInfo = [notification userInfo];
  //
  //    NSString *content = [userInfo valueForKey:@"content"];
  //
  //    NSLog(@"%@",content);
  //
  //    NSDictionary *extras = [userInfo valueForKey:@"extras"];
  //    NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //自定义参数,key是自己定义的
  //    
}
#pragma mark - 判断通知设置是够开启
-(void)examineAPPSettingAndSet
{
  if([[[UIDevice currentDevice] systemVersion] floatValue] > 8.0){
    //  8.0以后
    UIUserNotificationType type;
    UIUserNotificationSettings *mySet =
    [[UIApplication sharedApplication] currentUserNotificationSettings];
    type = mySet.types;
    if (type == UIUserNotificationTypeNone) {
      [self showAlertAndSeting];
    }
  }else
  {
    //  8.0及之前
    UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
    if (type == UIRemoteNotificationTypeNone) {
      [self showAlertAndSeting];
    }
  }
}
-(void)showAlertAndSeting
{
  if([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0){
    UIAlertView *tipMessage = [[UIAlertView alloc] initWithTitle:@"通知服务已关闭" message:Message_Notification_Without delegate:nil cancelButtonTitle:nil otherButtonTitles:@"知道了", nil];
    tipMessage.tag = 1001;
    [tipMessage show];
  }else{
    //8.0以后
    UIAlertView *tipSettingMessage=[[UIAlertView alloc] initWithTitle:@"通知服务已关闭" message:Message_Notification_Without delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
    tipSettingMessage.tag=1002;
    [tipSettingMessage show];
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,176评论 5 469
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,190评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,232评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,953评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,879评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,177评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,626评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,295评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,436评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,365评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,414评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,096评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,685评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,771评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,987评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,438评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,032评论 2 341

推荐阅读更多精彩内容