前台收到ios 前台处理推送消息息有办法在通知栏里显示吗

5823人阅读
---------------------------------------需要进一步测试--------------------------------------
当你的iPhone收到推送信息后到底会发生什么呢?总共有三种可能性:
app在前台运行. 接收到推送信息时屏幕上不会有任何显示,也不会有提示音,但你的app delegate会收到这个推送信息。你可以在这里加入代码来处理接收到的信息。
app不在前台运行。iPhone可能停留在主界面或者另一个app正在运行.一个提示窗口会弹出,可能伴随着提示音。用户可以点击Close按钮来关闭这个窗口或者点击View按钮来打开你的app。如果用户点击的时Close按钮,那你的app不会处理这个推送的信息。
iPhone在锁屏状态下. 同样一个提示窗口弹出,并伴随着提示音,但是这个窗口不会有Close和View按钮。屏幕解锁后会自动进入你的app。
因为app delegate是接收推送信息的地方,我们对app的最后改动都是在AppDelegate.m文件中。我们需要修改两处:
application:didFinishLaunchingWithOptions:函数. 如果推送信息到达时你的app不在前台运行,而用户在弹出窗口点击了“View”按钮,你的app会重新运行然后这个信息会作为参数注入到application:didFinishLaunchingWithOptions:函数中。
application:didReceiveRemoteNotification:函数. 如果信息到达时你的app正在前台运行,那这个函数就会被调用。在iOS4.0或更新的版本,如果你的app从暂停状态进入前台,这个函数也会被调用。你可以用UIApplication的applicationState属性来检查你的app是否是从暂停状态苏醒。
上述的两个函数都会有一个字典参数其中包含了JSON格式的推送信息内容。OS已经帮我们把JSON格式的信息转换成Objective-C字典了。将下面的代码加到didFinishLaunchingWithOptions:函数的return语句前:   if (launchOptions != nil)
NSDictionary* dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (dictionary != nil)
NSLog(@&Launched from push notification: %@&, dictionary);
[self addMessageFromRemoteNotification:dictionary updateUI:NO];
我们先确保launchOptions参数不是nil以及launchOptions中包含了推送信息。然后调用addMessageFromRemoteNotification函数来处理这个信息。
把下面的函数加到AppDelegate.m文件中:  - (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo
  NSLog(@&Received notification: %@&, userInfo);
[self addMessageFromRemoteNotification:userInfo updateUI:YES];
这个函数同样依靠addMessageFromRemoteNotification来完成处理信息的工作。
将下面这个函数复制粘贴到didFinishLaunchingWithOptions:函数上面:- (void)addMessageFromRemoteNotification:(NSDictionary*)userInfo updateUI:(BOOL)updateUI
Message* message = [[Message alloc] init];
message.date = [NSDate date];
NSString* alertValue = [[userInfo valueForKey:@&aps&] valueForKey:@&alert&];
NSMutableArray* parts = [NSMutableArray arrayWithArray:[alertValue componentsSeparatedByString:@&: &]];
message.senderName = [parts objectAtIndex:0];
[parts removeObjectAtIndex:0];
message.text = [parts componentsJoinedByString:@&: &];
int index = [dataModel addMessage:message];
if (updateUI)
[self.chatViewController didSaveMessage:message atIndex:index];
[message release];
我保证这是最后一点代码了。然我们解释一下这段代码。Message* message = [[Message alloc] init];
message.date = [NSDate date];
首先我们创建一个Message对象。我们会把推送信息的内容提取出来,填入到这个对象中然后将这个对象加入到DataModel中。NSString* alertValue = [[userInfo valueForKey:@&aps&] valueForKey:@&alert&];
上面的代码从推送信息中获取了信息的内容。推送信息的JSON的格式看起来是这样的:{
&alert&: &SENDER_NAME: MESSAGE_TEXT&,
&sound&: &default&
服务器把信息内容以及信息作者的昵称放到了“alert”栏中。我们对这个字典中的其他内容并不感兴趣。NSMutableArray* parts = [NSMutableArray arrayWithArray:[alertValue componentsSeparatedByString:@&: &]];
message.senderName = [parts objectAtIndex:0];
[parts removeObjectAtIndex:0];
message.text = [parts componentsJoinedByString:@&: &];
上面的代码将发送者的昵称和信息内容分解出来放入到Message对象中。发送者昵称是分号和空格之前的字符串。int index = [dataModel addMessage:message];
现在我们可以把这个Message对象加入到DataModel中了。if (updateUI)
[self.chatViewController didSaveMessage:message atIndex:index];
最后,我们让ChatViewController加入这个新的信息。但是,如果推送信息是在didFinishLaunchingWithOptions函数中收到的,那我们就不能刷新这个视图,因为那时ChatViewController的表格还没有加载。视图加入这个信息会导致系统崩溃的。
就这些了。编译并运行现有的程序。用test_message.html中的表格来发送一些信息。你应该在app的聊天视图中看到这些信息气泡出现。自定义提示信息
你应该还记得我们之前在介绍推送信息时曾说过你可以自定义提示设置。比如你可以在有信息时播放一个自定义的提示音。我在app的resources文件夹中放了一个音频文件叫做beep.caf。
打开api.php文件并在makePayload()函数中将下面这行代码:$payload = '{&aps&:{&alert&:&' . $nameJson . ': ' . $textJson . '&,&sound&:&default&}}';
改为:$payload = '{&aps&:{&alert&:&' . $nameJson . ': ' . $textJson . '&,&sound&:&beep.caf&}}';
你不需要改变app本身的任何代码,甚至不用重新编译。但你还是应该在设备上关闭打开了的app。因为如果我们的app正在前台运行,那提示音是不会响的。现在用test_message.html给app发一个信息。当提示窗口出现时,提示音是不是不同了?
你也可以实验修改其他的选项。比如提供自定义按钮,或者给app设定数量小图标。(如果你想实验数量小图标,别忘了让app注册接收数量图标。现在我们的app只会有提示音和提示窗口。)
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:729833次
积分:6453
积分:6453
排名:第3709名
原创:113篇
转载:103篇
评论:122条
(1)(1)(2)(1)(2)(6)(1)(3)(3)(8)(1)(4)(4)(5)(3)(5)(12)(11)(15)(10)(15)(3)(8)(12)(6)(9)(14)(5)(2)(2)(9)(12)(3)(1)(9)(6)(3)匿名用户不能发表回复!|
每天回帖即可获得10分可用分!小技巧:
你还可以输入10000个字符
(Ctrl+Enter)
请遵守CSDN,不得违反国家法律法规。
转载文章请注明出自“CSDN(www.csdn.net)”。如是商业用途请联系原作者。看到标题你可能会觉得奇怪 推送消息提示框不是系统自己弹出来的吗? 为什么还要自己自定义呢?
因为项目需求是这样的:最近需要做 远程推送通知 和一个客服系统 包括店铺客服和官方客服两个模块 如果有新的消息推送的时候 如果用户当前不在客服界面的时候 &要求无论是在app前台 还是app退到后台 顶部都要弹出系统的那种消息提示框
这样的需求 我们就只能自定义一个在app内 弹出消息提示框&
实现步骤如下:
1.我们自定义一个view 为 STPushView 推送消息的提示框view
#import &UIKit/UIKit.h&
#import "STPushModel.h"
@interface STPushView : UIView
/** *推送数据模型 */
@property(nonatomic,strong) STPushModel *
+(instancetype)shareI
#import "STPushView.h"
#import "AppDelegate.h"
@interface STPushView()
@property (nonatomic, weak) UIImageView *imageV;
@property (nonatomic,weak ) UILabel
@property (nonatomic,weak ) UILabel
@implementation STPushView
static STPushView *_instance =
+(instancetype)shareInstance
static dispatch_once_t onceT
dispatch_once(&onceToken, ^{
_instance = [[STPushView alloc] init];
+(instancetype) allocWithZone:(struct _NSZone *)zone
if (!_instance) {
_instance = [super allocWithZone:zone];
- (instancetype)initWithFrame:(CGRect)frame
if (self = [super initWithFrame:frame]) {
self.backgroundColor = CUSTOMCOLOR(15, 14, 12);
CGFloat margin = 12;
UIImageView *imageV = [[UIImageView alloc] init];
imageV.userInteractionEnabled = NO;
imageV.image = [UIImage imageNamed:@"logo"];
imageV.layer.cornerRadius = 5;
[self addSubview:imageV];
self.imageV = imageV;
[imageV mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self).offset(margin);
make.centerY.equalTo(self.mas_centerY);
make.width.mas_equalTo(30);
make.height.mas_equalTo(30);
UILabel *titleLabel = [[UILabel alloc] init];
titleLabel.textColor = [UIColor whiteColor];
titleLabel.font = [UIFont boldSystemFontOfSize:12];
titleLabel.text = @"121店官方客服";
[self addSubview:titleLabel];
[titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(imageV.mas_right).offset(margin);
make.top.equalTo(self.mas_top).offset(margin);
make.height.mas_equalTo(16);
[titleLabel sizeToFit];
UILabel *timLabel = [[UILabel alloc] init];
timLabel.font = [UIFont systemFontOfSize:12];
timLabel.userInteractionEnabled = NO;
timLabel.textColor = [UIColor whiteColor];
timLabel.text = @"刚刚";
timLabel.textColor = [UIColor lightGrayColor];
[self addSubview:timLabel];
self.timLabel = timL
[timLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(titleLabel.mas_right).offset(margin);
make.top.equalTo(self.mas_top).offset(margin);
make.width.mas_lessThanOrEqualTo(40);
make.height.mas_equalTo(16);
UILabel *content = [[UILabel alloc] init];
content.numberOfLines = 2;
content.font = [UIFont systemFontOfSize:13];
content.textColor = [UIColor whiteColor];
content.userInteractionEnabled = NO;
[self addSubview:content];
self.content =
[content mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(imageV.mas_right).offset(margin);
make.top.equalTo(titleLabel.mas_bottom).offset(-3);
make.right.equalTo(self.mas_right).offset(-margin);
make.height.mas_equalTo(35);
UIView *toolbar = [[UIView alloc] init];
toolbar.backgroundColor = CUSTOMCOLOR(121, 101, 81);
toolbar.layer.cornerRadius = 3;
[self addSubview:toolbar];
[toolbar mas_makeConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(35);
make.height.mas_equalTo(6);
make.centerX.equalTo(self.mas_centerX);
make.bottom.equalTo(self.mas_bottom).offset(-2);
- (void)setModel:(STPushModel *)model
self.timLabel.text = @"刚刚";
self.content.text = model.
+ (void)show
[UIApplication sharedApplication].statusBarHidden = YES;
STPushView *pushView = [STPushView shareInstance];
pushView.hidden = NO;
AppDelegate *app = (AppDelegate*)[UIApplication sharedApplication].delegate;
[app.window bringSubviewToFront:pushView];
[UIView animateWithDuration:0.25 animations:^{
pushView.frame = CGRectMake(0, 0, SCREEN_WIDTH, pushViewHeight);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[UIView animateWithDuration:0.25 animations:^{
pushView.frame = CGRectMake(0, -pushViewHeight, SCREEN_WIDTH, pushViewHeight);
} completion:^(BOOL finished) {
[UIApplication sharedApplication].statusBarHidden = NO;
pushView.hidden = YES;
+ (void)hide
STPushView *pushView = [STPushView shareInstance];
[UIView animateWithDuration:0.25 animations:^{
pushView.frame = CGRectMake(0, -pushViewHeight, SCREEN_WIDTH, pushViewHeight);
} completion:^(BOOL finished) {
[UIApplication sharedApplication].statusBarHidden = NO;
pushView.hidden = YES;
上面pushView需要一个模型 实现代码如下
// push 推送的model
推送过来的数据如下:
id = 5077;
mid = 1270339;
url = "3?_from=push";
urlType = 3;
#import &Foundation/Foundation.h&
@interface STPushModel : STBaseModel&NSCoding&
//STBaseModel 是一个继承自NSObject的类 我主要是在这个类中实现了字典转模型的功能 你可以直接修改为NSObject
@property (copy,nonatomic) NSString* recordId;
/***标题**/
@property (copy, nonatomic) NSString *
/***url**/
@property (copy, nonatomic) NSString *
/***url 类型**/
@property (copy, nonatomic) NSString* urlT
/***图标的高度**/
@property (assign,nonatomic) NSString *
/***推送内容**/
@property (copy, nonatomic) NSString*
因为涉及到好几个页面需要使用同样的推送消息数据 进行判断而处理相应的业务 所有我对此模型做了归档处理
#import "STPushModel.h"
@implementation STPushModel
保存对象到文件中
@param aCoder &#aCoder description#&
-(void)encodeWithCoder:(NSCoder *)aCoder
[aCoder encodeObject:self.recordId forKey:@"recordId"];
[aCoder encodeObject:self.title forKey:@"title"];
[aCoder encodeObject:self.url forKey:@"url"];
[aCoder encodeObject:self.urlType forKey:@"urlType"];
[aCoder encodeObject:self.mid forKey:@"mid"];
[aCoder encodeObject:self.content forKey:@"content"];
从文件中读取对象
@param aDecoder &#aDecoder description#&
@return &#return value description#&
-(id)initWithCoder:(NSCoder *)aDecoder
//注意:在构造方法中需要先初始化父类的方法
if (self=[super init]) {
self.recordId=[aDecoder decodeObjectForKey:@"recordId"];
self.title=[aDecoder decodeObjectForKey:@"title"];
self.url=[aDecoder decodeObjectForKey:@"url"];
self.urlType=[aDecoder decodeObjectForKey:@"urlType"];
self.mid=[aDecoder decodeObjectForKey:@"mid"];
self.content= [aDecoder decodeObjectForKey:@"content"];
做好了上面的准备工作之后 &接下来我们就需要 APPdelegate里面注册远程推送通知 &并且监听推送消息
这里以个推为例子:
第一步在下面的方法中 实现个推的注册方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 注册个推推送服务
[[GeTuiApilmpl sharedInstance] geTuiRegister];
GeTuiApilmpl 是一个单例类 专门用于注册个推的推送方法
实现代码如下:
#import &Foundation/Foundation.h&
#import "GeTuiSdk.h"
@interface GeTuiApilmpl : NSObject &GeTuiSdkDelegate&
+ (GeTuiApilmpl *) sharedI
- (void) geTuiR
#import "GeTuiApilmpl.h"
@implementation GeTuiApilmpl
+ (GeTuiApilmpl *) sharedInstance{
static id instance =
static dispatch_once_t onceT
dispatch_once(&onceToken, ^{
instance = [[self alloc] init];
#pragma mark - GeTuiSdkDelegate
/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
// [4-EXT-1]: 个推SDK已注册,返回clientId
NSLog(@"\n&&&[GeTuiSdk RegisterClient]:%@\n\n", clientId);
/** SDK遇到错误回调 */
- (void)GeTuiSdkDidOccurError:(NSError *)error {
// [EXT]:个推错误报告,集成步骤发生的任何错误都在这里通知,如果集成后,无法正常收到消息,查看这里的通知。
NSLog(@"\n&&&[GexinSdk error]:%@\n\n", [error localizedDescription]);
/** SDK收到透传消息回调 */
- (void)GeTuiSdkDidReceivePayload:(NSString *)payloadId andTaskId:(NSString *)taskId andMessageId:(NSString *)aMsgId andOffLine:(BOOL)offLine fromApplication:(NSString *)appId {
// [4]: 收到个推消息
NSData *payload = [GeTuiSdk retrivePayloadById:payloadId];
NSString *payloadMsg =
if (payload) {
payloadMsg = [[NSString alloc] initWithBytes:payload.bytes length:payload.length encoding:NSUTF8StringEncoding];
NSString *msg = [NSString stringWithFormat:@" payloadId=%@,taskId=%@,messageId:%@,payloadMsg:%@%@", payloadId, taskId, aMsgId, payloadMsg, offLine ? @"&离线消息&" : @""];
NSLog(@"\n&&&[GexinSdk ReceivePayload]:%@\n\n", msg);
*汇报个推自定义事件
*actionId:用户自定义的actionid,int类型,取值。
*taskId:下发任务的任务ID。
*msgId: 下发任务的消息ID。
*返回值:BOOL,YES表示该命令已经提交,NO表示该命令未提交成功。注:该结果不代表服务器收到该条命令
[GeTuiSdk sendFeedbackMessage:90001 taskId:taskId msgId:aMsgId];
/** SDK收到sendMessage消息回调 */
- (void)GeTuiSdkDidSendMessage:(NSString *)messageId result:(int)result {
// [4-EXT]:发送上行消息结果反馈
NSString *msg = [NSString stringWithFormat:@"sendmessage=%@,result=%d", messageId, result];
NSLog(@"\n&&&[GexinSdk DidSendMessage]:%@\n\n", msg);
/** SDK运行状态通知 */
- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus {
// [EXT]:通知SDK运行状态
NSLog(@"\n&&&[GexinSdk SdkState]:%u\n\n", aStatus);
/** SDK设置推送模式回调 */
- (void)GeTuiSdkDidSetPushMode:(BOOL)isModeOff error:(NSError *)error {
if (error) {
NSLog(@"\n&&&[GexinSdk SetModeOff Error]:%@\n\n", [error localizedDescription]);
NSLog(@"\n&&&[GexinSdk SetModeOff]:%@\n\n", isModeOff ? @"开启" : @"关闭");
-(void)geTuiRegister{
NSString *path = [[NSBundle mainBundle] pathForResource:@"libGexin" ofType:@"plist"];
NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
[GeTuiSdk startSdkWithAppId:[dic objectForKey:@"GT_APPID"]
appKey:[dic objectForKey:@"GT_APPKEY"]
appSecret:[dic objectForKey:@"GT_APPSECRET"]
delegate:self];
上面的&libGexin.plist 的配置内容如下:
然后再appDelegate 调用注册远程推送的方法&
/** 注册用户通知 */
- (void)registerUserNotification {
注册通知(推送)
申请App需要接受来自服务商提供推送消息
// 判读系统版本是否是&iOS 8.0&以上
if ([[[UIDevice currentDevice] systemVersion] floatValue] &= 8.0 ||
[UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]) {
// 定义用户通知类型(Remote.远程 - Badge.标记 Alert.提示 Sound.声音)
UIUserNotificationType types = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeS
// 定义用户通知设置
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
// 注册用户通知 - 根据用户通知设置
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
} else { // iOS8.0 以前远程推送设置方式
// 定义远程通知类型(Remote.远程 - Badge.标记 Alert.提示 Sound.声音)
UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeS
// 注册远程通知 -根据远程通知类型
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
然后在AppDelegate的&didFinishLaunchingWithOptions 写上如下代码:
调用:addPushView方法 添加 消息提示框STPushView: &addPushView实现代码如下
#pragma mark 推送信息展示
//添加推送view
- (void)addPushView
STPushView *topView = [STPushView shareInstance];
topView.frame = CGRectMake(0, -pushViewHeight, SCREEN_WIDTH, pushViewHeight);
[_window addSubview:topView];
self.topView = topV
topView.hidden = YES;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hudClick)];
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[topView addGestureRecognizer:tap];
[tap requireGestureRecognizerToFail:pan];
topView.gestureRecognizers = @[tap,pan];
#pragma mark
addPushView相关事件
- (void)hudClick
self.topView.userInteractionEnabled = NO;
[UIView animateWithDuration:0.25 animations:^{
self.topView.frame = CGRectMake(0, -pushViewHeight, SCREEN_WIDTH, pushViewHeight);
}completion:^(BOOL finished) {
[UIApplication sharedApplication].statusBarHidden = NO;
[self hudClickOperation];
- (void)hudClickOperation
[self push:nil];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.topView.userInteractionEnabled = YES;
- (void)pan:(UIPanGestureRecognizer*)pan
CGFloat distance = pushViewHeight-(pushViewHeight-[pan translationInView:self.window].y);
if (distance&-20) {
[UIView animateWithDuration:0.25 animations:^{
self.topView.frame = CGRectMake(0, -pushViewHeight, SCREEN_WIDTH, pushViewHeight);
}completion:^(BOOL finished) {
[UIApplication sharedApplication].statusBarHidden = NO;
//显示pushView
- (void)displayPushView
[STPushView show];
上面push方法的实现代码如下: 处理逻辑 是根据我自己的项目中需求定的 在这里实现你需要处理的代码
- (void)push:(NSDictionary *)params{
STPushModel *model = [ NSKeyedUnarchiver unarchiveObjectWithFile:KRAPI_PUSH_DATA];
//如果是h5
if ([model.urlType isEqualToString:@"h5"]) {
BOOL isStore = [[AnalysisUrl sharedInstance] analysisWebUrl:model.url];
BOOL isGoods = [[AnalysisUrl sharedInstance] analysisGoodsIdWebUrl:model.url];
BOOL isRedBag =[[AnalysisUrl sharedInstance] analyredBagWebUrl:model.url];
BOOL istrace =[[AnalysisUrl sharedInstance] analytraceWebUr:model.url];
BOOL islog =[[AnalysisUrl sharedInstance] analylogWebUrl:model.url];
if (isStore || isGoods) {
[[WYPageManager sharedInstance] pushViewControllerWithUrlString:model.url currentUrlString:TRAKER_URL_INDEX];
}else if (isRedBag)
RedBageViewController * regBag =[[RedBageViewController alloc]init];
NSArray *array = [model.url componentsSeparatedByString:@"="];
NSString * string = [array lastObject];
regBag.messageID = string;
regBag.redType = @"coupon";
UITabBarController *tabVC = (UITabBarController *)self.window.rootViewC
UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex];
// 跳转到对应的控制器
regBag.hidesBottomBarWhenPushed = YES;
[pushClassStance pushViewController:regBag animated:YES];
}else if (istrace)
RedBageViewController * regBag =[[RedBageViewController alloc]init];
NSString * string = [StrUtils getIdFromURLString:model.url interceptString:@"/trace/"];
regBag.messageID = string;
regBag.redType = @"trace";
UITabBarController *tabVC = (UITabBarController *)self.window.rootViewC
UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex];
// 跳转到对应的控制器
regBag.hidesBottomBarWhenPushed = YES;
[pushClassStance pushViewController:regBag animated:YES];
}else if (islog)
RedBageViewController * regBag =[[RedBageViewController alloc]init];
NSString * string = [StrUtils getIdFromURLString:model.url interceptString:@"/log/"];
regBag.messageID = string;
regBag.redType = @"log";
UITabBarController *tabVC = (UITabBarController *)self.window.rootViewC
UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex];
// 跳转到对应的控制器
regBag.hidesBottomBarWhenPushed = YES;
[pushClassStance pushViewController:regBag animated:YES];
if (![model.url isEqualToString:@""]) {
UIStoryboard *setStoryboard = [UIStoryboard storyboardWithName:@"UserCenter" bundle:nil];
TotalWebViewController *setVC = [setStoryboard instantiateViewControllerWithIdentifier:@"TotalWebViewController"];
setVC.shopUrl = model.
setVC.shopTitle = [model.title isEqualToString:@""] ? @"121店" : model.
UITabBarController *tabVC = (UITabBarController *)self.window.rootViewC
UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex];
setVC.hidesBottomBarWhenPushed = YES;
[pushClassStance pushViewController:setVC animated:YES];
}else if ([model.urlType isEqualToString:@"native"]){
if ([model.url isEqualToString:@"1"]) {
//一元体验购 已经删除
}else if ([model.url isEqualToString:@"2"]){
if (([[STCommonInfo getAuthType] intValue] != 1)) {
[self createGroundGlass];
STProFitViewController *vc = [[STProFitViewController alloc] init];
UITabBarController *tabVC = (UITabBarController *)self.window.rootViewC
UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex];
vc.hidesBottomBarWhenPushed = YES;
[pushClassStance pushViewController:vc animated:YES];
}else if ([model.url isEqualToString:@"3"]){
if (([[STCommonInfo getAuthType] intValue] != 1)) {
[self createGroundGlass];
MessageMainVC *messageVC = [[MessageMainVC alloc] init];
messageVC.hidesBottomBarWhenPushed = YES;
UITabBarController *tabVC = (UITabBarController *)self.window.rootViewC
UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex];
[pushClassStance pushViewController:messageVC animated:YES];
}else if ([model.url hasPrefix:@"http://"]&&([model.url rangeOfString:@"client"].location!=NSNotFound)){ //跳转到客服接 界面
NSString *orgIdString =[[AnalysisUrl sharedInstance] extractOrgId:model.url];
NSString *siteIdString = [[AnalysisUrl sharedInstance] extractOrgIdStoreId:model.url];
[[WYPageManager sharedInstance] pushViewController:@"TLChatViewController" withParam:
@"title_nameString":@"官方客服",
@"orgIdString":orgIdString,
@"siteIdString":siteIdString,
@"currentURL":model.url
} animated:YES];
然后再AppDelegate 实现以下方法
/** 自定义:APP被&推送&启动时处理推送消息处理(APP 未启动--》启动)*/- (void)receiveNotificationByLaunchingOptions:(NSDictionary *)launchOptions {
if (!launchOptions)
通过&远程推送&启动APP
UIApplicationLaunchOptionsRemoteNotificationKey 远程推送Key
NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (userInfo) {
NSLog(@"\n&&&[Launching RemoteNotification]:%@", userInfo);
#pragma mark - 用户通知(推送)回调 _IOS 8.0以上使用
/** 已登记用户通知 */
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
// 注册远程通知(推送)
[application registerForRemoteNotifications];
#pragma mark - 远程通知(推送)回调
/** 远程通知注册成功委托 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *myToken = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"&&"]];
myToken = [myToken stringByReplacingOccurrencesOfString:@" " withString:@""];
NSUserDefaults *kr = [NSUserDefaults standardUserDefaults];
[kr setValue:myToken forKey:@"deviceToken"];
[kr synchronize];
[GeTuiSdk registerDeviceToken:myToken];
[[PostDeviceToken sharedInstance] postUpDeviceToken];
NSLog(@"\n&&&[DeviceToken Success]:%@\n\n", myToken);
/** 远程通知注册失败委托 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
[GeTuiSdk registerDeviceToken:@""];
NSLog(@"\n&&&[DeviceToken Error]:%@\n\n", error.description);
#pragma mark - APP运行中接收到通知(推送)处理
/** APP已经接收到&远程&通知(推送) - 透传推送消息
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
// 处理APN
NSLog(@"\n&&&[Receive RemoteNotification - Background Fetch]:%@\n\n", userInfo);
completionHandler(UIBackgroundFetchResultNewData);
NSUserDefaults *kr = [NSUserDefaults standardUserDefaults];
NSData *jsonData = [payLoadString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:nil];
STPushModel *model = [STPushModel modelObjectWithDict:jsonDic];
[NSKeyedArchiver archiveRootObject:model toFile:KRAPI_PUSH_DATA];
//如果应用程序在前台 就显示客服提示框
if (application.applicationState == UIApplicationStateActive) {
self.topView.model =
[self displayPushView];
//此方法 的实现 在上一步中 就是展示提示框出来
然后这些工作做好了之后 就是你需要在个推的后台 配置推送证书 &这个配置的步骤 大家可以到个推官网去参考文档 配置&
这里我假设 你已经配置到证书了 &经过上面的步骤 我们的远程推送通知的方法 基本完成 现在我们运行 测试下 你会发现即使在前台 有新消息推送的时候 顶部也会弹出和系统一样的提示框 点击 跳转到对应的页面的方法逻辑根据你的需要 去做跳转处理
测试效果如下:
用户在后台 收到的消息提示如下:
用户在前台 收到的消息提示如下:
阅读(...) 评论()

我要回帖

更多关于 安卓通知栏消息推送 的文章

 

随机推荐