阿里云移动推送iOS

时间:2022-09-25 20:45:44

前言

阿里云移动推送的集成这里不做重复描述,可以自己查看文档。

一、分类

阿里云推送主要分通知和消息两种。
如果安装在苹果手机上接受到的场景可以分为三类:
1、APP在杀死状态下,收到通知;
2、APP在进入后台状态下,收到通知;
3、APP在前台活跃状态下,收到通知;

1、消息

消息还是比较简单的,APP在前台就可以收到消息,用于更新数据等。

/**
* 注册推送消息到来监听
*/

- (void)registerMessageReceive {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(onMessageReceived:)
name:@"CCPDidReceiveMessageNotification"
object:nil];
}

/**
* 处理到来推送消息
*
*/

- (void)onMessageReceived:(NSNotification *)notification {
CCPSysMessage *message = [notification object];
NSString *title = [[NSString alloc] initWithData:message.title encoding:NSUTF8StringEncoding];
NSString *body = [[NSString alloc] initWithData:message.body encoding:NSUTF8StringEncoding];
NSLog(@"Receive message title: %@, content: %@.", title, body);

NSDictionary *info = @{@"title":title,@"body":body};
[[NSNotificationCenter defaultCenter] postNotificationName:@"message_notification" object:nil userInfo:info];
}

2、APP在杀死状态下,收到通知

这是比较常见的,也是最经典的通知方式。当APP处于杀死状态下,手机展示通知栏,点击通知启动APP可以获取发送的数据。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// launchOptions为通知的内容
}

3、APP退出到后台,收到通知

APP退出到后台,并没有被系统或者手动杀死,这时收到推送进行如下处理:

/*
* App处于启动状态时,通知打开回调
*/

- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo {
NSLog(@"Receive one notification.");
// 取得APNS通知内容
NSDictionary *aps = [userInfo valueForKey:@"aps"];
// 内容
NSString *content = [aps valueForKey:@"alert"];
// badge数量
NSInteger badge = [[aps valueForKey:@"badge"] integerValue];
// 播放声音
NSString *sound = [aps valueForKey:@"sound"];
// 取得Extras字段内容
NSString *Extras = [userInfo valueForKey:@"Extras"]; //服务端中Extras字段,key是自己定义的
NSLog(@"content = [%@], badge = [%ld], sound = [%@], Extras = [%@]", content, (long)badge, sound, Extras);
// iOS badge 清0
application.applicationIconBadgeNumber = 0;
// 通知打开回执上报
// [CloudPushSDK handleReceiveRemoteNotification:userInfo];(Deprecated from v1.8.1)
[CloudPushSDK sendNotificationAck:userInfo];

[[NSNotificationCenter defaultCenter] postNotificationName:@"remote_notification" object:nil userInfo:userInfo];
}

二、点击APP启动程序

1、在APP杀死状态,来了通知,点击APP的图标打开APP并不能接收到推送的消息。
2、APP在后台,来了通知,点击APP的图标激活APP也不能收到消息。