美文网首页
iOS-推送

iOS-推送

作者: Freedom_fly | 来源:发表于2017-08-23 17:07 被阅读3次

使用苹果原生推送

1、注册推送:

1.1> 导入:

import <UserNotifications/UserNotifications.h>

1.2> 协议:

<UNUserNotificationCenterDelegate>

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"]) {
            // 跳转页面
        }
    }
}

相关文章

  • 03.iOS本地推送通知

    @(〓〓 iOS-实用技术)[远程/本地推送] 作者: Liwx 邮箱: 1032282633@qq.com 目...

  • 04.iOS远程推送通知 APNs远程推送,极光推送

    @(〓〓 iOS-实用技术)[远程/本地推送] 作者: Liwx 邮箱: 1032282633@qq.com 目...

  • iOS-集成UMeng消息推送遇到的坑货🔥

    iOS-集成UMeng消息推送遇到的坑货? 关于umeng的推送集成教程查看上一篇文章: 基于UMeng消息推送测...

  • iOS-推送

    使用苹果原生推送 1、注册推送: 1.1> 导入: import 1.2> 协议: 1.3> 开始注册推送: (B...

  • iOS-推送相关

    推送消息出现情景和处理办法 1. 当程序处于关闭状态收到推送消息时,点击推送图标会调用- (BOOL)applic...

  • iOS-消息推送

    iOS 消息推送包括远程推送通知(Remote Notification)和本地推送通知(Local Notifi...

  • iOS-推送详解

    准备篇 Tip 1:推送通知(Push Notification)必须购买Apple开发者账号,并使用特定的推送证...

  • iOS-推送(基础)

    一、iOS推送原理 IOS推送消息是许多IOS应用都具备的功能,最近也在研究这个功能,参考了很多资料终于搞定了,下...

  • iOS-推送(模拟上架推送)

    个推和极光的推送功能几乎一致。本次以极光推送做为例子,验证生产环境推送证书。(开发环境很简单,看官网文档就行OK了...

  • iOS-消息推送之远程推送和本地推送

    一、原生开发推送 今天看到一篇很详细的关于推送的相关文章,一系列的本地推送和远程推送都有,收藏下来,以备后用! 推...

网友评论

      本文标题:iOS-推送

      本文链接:https://www.haomeiwen.com/subject/jazddxtx.html