本文最后更新于:2021年12月22日 中午
一 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 { ... [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) { ... } [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) { 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 { [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; }
- (void)applicationWillEnterForeground:(UIApplication *)application { [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; }
|
联系方式
邮箱: xiebangyao_1994@163.com
相关账号: