【iOS笔记】【19】iOS远程推送流程

本文最后更新于:2021年12月22日 中午

【主页】系列文章目录

【iOS笔记】系列目录


一 iOS消息推送流程

  • 1.由App向iOS设备发送一个注册通知,用户需要同意系统发送推送
  • 2.iOS应用向APNS远程推送服务器发送App的Bundle Id和Device UUID
  • 3.APNS根据设备的UUID和App的Bundle Id生成deviceToken再发回App
  • 4.App再将deviceToken发送给远程推送服务器(自己的服务器),再由服务器保存到数据库中
  • 5.当自己的服务器想发送推送时,在远程推送服务器中输入想发送的消息并选择发给哪些用户的deviceToken,由远程推送服务器发送给APNS
  • 6.APNS根据deviceToken发送给对应的用户

    二 相关代码

1.获取DeviceToken

1
2
3
4
5
6
7
8
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// do some initiale working
...

[application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
return YES;
}
1).处理成功回调
1
2
3
4
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(@"Receive DeviceToken: %@", deviceToken);
// 上传自家服务器
}
2).处理失败回调
1
2
3
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"注册失败,无法获取设备ID, 具体错误: %@", error);
}

2.处理接收消息回调

1)、App未启动

1
2
3
4
5
6
7
8
9
10
11
12
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if (launchOptions) {
// do something else
...

}

[application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];

return YES;
}

2)、App正在运行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
if (application.applicationState == UIApplicationStateActive) {
// App在前台
// 转换成一个本地通知,显示到通知栏,你也可以直接显示出一个alertView,只是那样稍显aggressive:)
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.userInfo = userInfo;
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.alertBody = [userInfo objectForKey:@"alertInfo"];
localNotification.fireDate = [userInfo objectForKey:@"date"];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
} else {
// 后台到前台
}
}

3.处理小红点

1
2
3
4
5
6
7
8
- (void)applicationDidEnterBackground:(UIApplication *)application {
//设置应用程序图片右上角的数字(如果想要取消右上角的数字, 直接把这个参数值为0)
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

联系方式

邮箱: xiebangyao_1994@163.com

相关账号: