使用苹果原生推送
1、注册推送:
1.1> 导入:
import
1.2> 协议:
1.3> 开始注册推送:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法中注册
代码如下:
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!error) {
NSLog(@"succeeded!");
}
}];
}else if([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 && [[UIDevice currentDevice].systemVersion doubleValue] < 10.0) {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];// 本地推送
[[UIApplication sharedApplication] registerForRemoteNotifications]; // 远程推送
}else{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
}
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
[[UIApplication sharedApplication] registerForRemoteNotifications];
1.4> 注册回调:
#pragma mark - 注册通知回调
//如果推送通知注册成功,则自动调用这个方法
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
// 注册成功
NSString *pushToken = [[[[deviceToken description]
stringByReplacingOccurrencesOfString:@"<" withString:@""]
stringByReplacingOccurrencesOfString:@">" withString:@""]
stringByReplacingOccurrencesOfString:@" " withString:@""] ;
NSLog(@"注册推送deviceToken:%@",pushToken); // 可存储传给后台用于后续推送
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"注册推送服务时,发生�以下错误: %@", error);
}
2、发推送:
远程推送是由服务端进行操作,前端只需打开推送的开关及提供后台P12文件即可,所以下文描述的是如何发本地推送。
发送前先判断用户是否允许推送
if ([[UIApplication sharedApplication] currentUserNotificationSettings].types != UIUserNotificationTypeNone) { // 发推送 }
2.1> 发本地推送
if ([[UIApplication sharedApplication] currentUserNotificationSettings].types != UIUserNotificationTypeNone) {
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
// iOS10 发本地推送
// 1、创建通知内容,注:这里得用可变类型的UNMutableNotificationContent,否则内容的属性是只读的
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
// 标题 title 次标题 subtitle
content.title = @"iOS10本地推送";
content.body = @"iOS10-您有一条本地推送需查看";
content.sound = [UNNotificationSound defaultSound]; // 通知声音
content.categoryIdentifier = @"ZebraLocalNotification"; //标识符
[UIApplication sharedApplication].applicationIconBadgeNumber = 1;
// 2、创建通知触发
/* 触发器分三种:
UNTimeIntervalNotificationTrigger : 在一定时间后触发,如果设置重复的话,timeInterval不能小于60
UNCalendarNotificationTrigger : 在某天某时触发,可重复
UNLocationNotificationTrigger : 进入或离开某个地理区域时触发
*/
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:1 repeats:NO];
// 3、创建通知请求
UNNotificationRequest *notificationRequest = [UNNotificationRequest requestWithIdentifier:@"KFGroupNotification" content:content trigger:trigger];
// 4、将请求加入通知中心
[[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:notificationRequest withCompletionHandler:^(NSError * _Nullable error) {
if (error == nil) {
NSLog(@"已成功加推送%@",notificationRequest.identifier);
locaLNotificationFlag = YES;
}
}];
}else if([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 && [[UIDevice currentDevice].systemVersion doubleValue] < 10.0) {
// iOS8 发本地推送
UILocalNotification *notification = [[UILocalNotification alloc] init];
NSDate *pushDate = [NSDate dateWithTimeIntervalSinceNow:7];
if (notification != nil) {
notification.fireDate = pushDate;
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.repeatInterval = 0;
notification.soundName = UILocalNotificationDefaultSoundName;
notification.alertTitle = @"iOS8本地推送";
notification.alertBody = @"iOS8-您有一条本地推送需查看";
//显示在icon上的数字
notification.applicationIconBadgeNumber = 1;
//设置userinfo 方便在之后需要撤销的时候使用
NSDictionary *info = [NSDictionary dictionaryWithObject:@"localNotification"forKey:@"key"];
notification.userInfo = info;
//添加推送到UIApplication
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
locaLNotificationFlag = YES;
}
}
}
3、推送接收:
3.1> iOS8本地推送接收:
#pragma mark - iOS8本地推送
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
if (application.applicationState == UIApplicationStateActive) {
// 前台
NSMutableDictionary *content = [[NSMutableDictionary alloc] init];
[content setObject:notification.alertTitle forKey:@"content"];
[content setObject:notification.alertBody forKey:@"body"];
// 弹窗
UIAlertController *alertvc = [UIAlertController alertControllerWithTitle:content[@"content"] message:content[@"body"] preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* updateAction = [UIAlertAction actionWithTitle:@"查看" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
notification.applicationIconBadgeNumber = 0;
// 跳转页面
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"忽略" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
notification.applicationIconBadgeNumber = 0;
}];
[alertvc addAction:cancelAction];
[alertvc addAction:updateAction];
[[iChe_FirstViewController shareFirstViewController] presentViewController:alertvc animated:YES completion:nil];
return;
}
// 后台点击
notification.applicationIconBadgeNumber = 0;
NSString *value = [notification.userInfo objectForKey:@"key"];
if ([value isEqualToString:@"localNotification"]) {
// 跳转到指定页面
}
}
3.2> iOS8远程推送接收
#pragma mark - iOS8远程推送
// 不管app是在前台运行还是在后台运行,系统收到推送时都会调用该方法
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler {
if (application.applicationState == UIApplicationStateActive) {
// APP处于前台
NSString *message = [[userInfo objectForKey:@"aps"]objectForKey:@"alert"];
UIAlertController *alertvc = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* updateAction = [UIAlertAction actionWithTitle:@"查看" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
application.applicationIconBadgeNumber = 0;
if (userInfo.count) {
// 拿到信息跳转
}
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"忽略" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
application.applicationIconBadgeNumber = 0;
}];
[alertvc addAction:cancelAction];
[alertvc addAction:updateAction];
[[iChe_FirstViewController shareFirstViewController] presentViewController:alertvc animated:YES completion:nil];
}else {
// 后台 、杀掉进程
if (userInfo.count) {
// 拿到信息跳转
}
}
}
3.3> iOS10推送接收
#pragma mark - iOS10推送回调
// 当用户处于前台时,消息发送前走这个方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
// APP处于前台收到推送时,以通知栏展示消息
completionHandler(UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound);
}
}
// 通知交互走这个方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
NSString *categoryIdentifier = response.notification.request.content.categoryIdentifier;
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
// 数据位置:response.notification.request.content.userInfo
// 判断是否为本地通知
if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
NSDictionary *userInfo = response.notification.request.content.userInfo;
if (userInfo.count) {
if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
// 前台
}else {
// 程序唤醒、重新启动
}
}
} else {
// 本地推送
if ([categoryIdentifier isEqualToString:@"ZebraLocalNotification"]) {
// 跳转页面
}
}
}