iOS第三方之推送

作者: 平安喜乐698 | 来源:发表于2018-10-28 13:41 被阅读13次
目录
    1. 原生推送
    2. 极光推送

代码从笔记中摘录,有点老旧

原生推送(可以通过后台代码进行推送,但是Andorid不支持)

极光推送(可通过后台代码/极光网站进行推送)
个推(可通过后台代码推送,网站仅支持Android)
goEasy(只能给Web推送)
百度云
1. 原生推送
1. 苹果开发者中心编辑对应identify:打开通知功能并添加开发、发布推送证书(下载后双击安装,在钥匙串导出p12格式给后台)。
    每次编辑完APPID,需要更新描述文件
2.在项目 | Capabilities 选项卡下:打开通知功能,并勾选Backgroud Modes下的Remote notifications(允许App在后台时接收推送)
1 2
3.AppDelegate.m

/** 
1.注册推送
 */
-(void)registerPush{
    
    //
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 // Xcode 8编译会调用
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        // 小角标、声音、弹窗
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
            if (!error) {
                NSLog(@"request authorization succeeded!");
            }
        }];
        
        [[UIApplication sharedApplication] registerForRemoteNotifications];
#else // Xcode 7编译会调用
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
#endif
    } else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    } else {
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |
                                                                       UIRemoteNotificationTypeSound |
                                                                       UIRemoteNotificationTypeBadge);
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
    }

}


/**
 2.1注册APNs失败
 */
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"注册APNS失败:%@",error);
}
/** 2.2注册通知成功
 */
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    
    // 收到token
    NSString *token =
    [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"
                                                           withString:@""]
      stringByReplacingOccurrencesOfString:@">"
      withString:@""]
     stringByReplacingOccurrencesOfString:@" "
     withString:@""];

        // 保存到后台-用于推送
}


/**3.收到通知内容
 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
        
    // Required, iOS 7 Support
    completionHandler(UIBackgroundFetchResultNewData);

    // 清空角标
    [UIApplication sharedApplication].applicationIconBadgeNumber=-1;
    
    // 根据userInfo[@""] 发送各种类型的通知        
    [[NSNotificationCenter defaultCenter]postNotificationName:QUICK object:nil userInfo:userInfo];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    //
    NSLog(@"22222");
}

JAVA后台

jar

            bcprov-jdk16-145-1.jar  commons-io-2.0.1.jar commons-lang-2.5.jar
            commons-logging.jar  javaPNS_2.2.jar  javapns-jdk16-163.jar  log4j-1..2.16.jar

代码片段


                /**
                 * 发送推送
                 */
                String deviceToken = tokenFacade.selectTokenByUserId(customerId,"1");
                // 如果该用户存在token(登录状态)
                if (null != deviceToken && !"".equals(deviceToken)) {
                    int badge = 1;// 图标小红圈的数值
                    String sound = "default";// 铃音
                    List<String> tokens = new ArrayList<String>();
                    tokens.add(deviceToken);
                    //String certificatePath = "YotoPushDev.p12";
                    String certificatePath = "YoToPushStore.p12";
                    String certificatePassword = "xxxxxxxxx";// 此处注意导出的证书密码不能为空因为空密码会报错
                    
                    boolean sendCount = true;
                    PushNotificationPayload payLoad = new PushNotificationPayload();
                    payLoad.addAlert(msg3); // 消息内容
                    payLoad.addBadge(badge); // iphone应用图标上小红圈上的数值
                    
                    //payLoad.addCustomDictionary("publishId", publish.getId());
                    
                    if (!StringUtils.isBlank(sound)) {
                        payLoad.addSound(sound);// 铃音
                    }
                    PushNotificationManager pushManager = new PushNotificationManager();
                    // true:表示的是产品发布推送服务 false:表示的是产品测试推送服务
                    pushManager.initializeConnection(
                            new AppleNotificationServerBasicImpl(certificatePath, certificatePassword, false));
                    List<PushedNotification> notifications = new ArrayList<PushedNotification>();
                    
                    // 发送push消息
                    if (sendCount) {
                        Device device = new BasicDevice();
                        device.setToken(tokens.get(0));
                        PushedNotification notification = pushManager.sendNotification(device, payLoad, true);
                        notifications.add(notification);
                        System.out.println("发送推送。。");
                    } else {
                        List<Device> device = new ArrayList<Device>();
                        for (String token : tokens) {
                            device.add(new BasicDevice(token));
                        }
                        notifications = pushManager.sendNotifications(payLoad, device);
                    }
                    pushManager.stopConnection();
                    logger.info("  推送成功  :   ");
                }
2. 极光推送

简介

分为2种:
  [后台->]极光服务器->APNs->应用
  [后台->]极光服务器->应用  
  第一种通过APNs发送消息,应用关闭后仍然可接收消息。
  第二种(应用内推送)是应用启动后建立长连接发送消息,应用关闭后无法接收消息。

和原生APNs相比,优势:
    1、可以直接通过极光官网发送消息,减少开发成本。
    2、可以向iOS、Android、网页发送消息。
    3、提供应用内推送。

透传消息
    相对于推送消息,客户端不会进行通知栏提示和语音提示,直接在代码中处理。

使用

 1.
    在苹果开发者中心创建identify并勾选push notification添加开发、生产推送证书,下载后双击并导出为.p12格式。
    注册极光账号并创建应用,添加.p12格式的2个推送证书,拿到AppId、AppKey替换以下即可
 2.
    项目|CApabilities|打开Push Notifacition、打开Background Modes(勾选Remote notification)
    cocoaPods中加pod 'JPush'
 3. 
    AppDelegate

AppDelegate

#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif


<JPUSHRegisterDelegate>


配置
    // 配置推送(弹窗,角标,声音)
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
#endif
    } else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        // categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    
    
    // 1. 在极光推送注册本应用(如不需要使用IDFA,advertisingIdentifier 可为nil)
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:advertisingId];

    /*
    // 获取 :极光对每一个设备的唯一标示
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功:%@",registrationID);
            WriteForLocation(registrationID, @"pushToken");
        }else{
            NSLog(@"registrationID获取失败,code:%d",resCode);
        }
    }];
     */



// 2. APNs注册成功,获取TOKEN ,发送到极光推送
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    [JPUSHService registerDeviceToken:deviceToken];
}
// 2.1 APNs注册失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  //Optional
  NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
// 3. 收到推送时调用
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{

    //
    [JPUSHService handleRemoteNotification:userInfo];

    //
    NSLog(@"iOS6及以下系统,收到通知:%@", [self log:userInfo]);
}
// 3.1 收到推送时调用
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    
    //
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);

    //
    NSLog(@"iOS7及以上系统,收到通知:%@", [self log:userInfo]);
}

// 3.2 收到推送,即将显示推送时调用(iOS10)
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
// 收到推送(iOS10) 点击通知进入App时触发,
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    // request
    UNNotificationRequest *request = response.notification.request;
    // content
    UNNotificationContent *content = request.content;
    // 角标
    NSNumber *badge = content.badge;
    // 消息体
    NSString *body = content.body;
    // 声音
    UNNotificationSound *sound = content.sound;
    // 副标题
    NSString *subtitle = content.subtitle;
    // 标题
    NSString *title = content.title;
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];

        NSLog(@"iOS10 收到远程通知:%@", [self log:userInfo]);
    }else {
        // 判断为本地通知
        NSLog(@"iOS10 收到本地通知:{\nbody:%@,\ntitle:%@,\nsubtitle:%@,\nbadge:%@,\nsound:%@,\nuserInfo:%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    
    completionHandler();  // 系统要求执行这个方法
}
App在前台获取到通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // 同上
    NSDictionary * userInfo = notification.request.content.userInfo;
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
}
#endif



// 用于打印信息
- (NSString *)log:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str = [NSPropertyListSerialization propertyListWithData:tempData options:NSPropertyListImmutable format:NULL error:NULL];
    if (str==nil){
        str = [NSString stringWithFormat:@"%@",dic];
    }    
    
    return str;
}

    // 清除App角标
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    // 清除极光角标
    [JPUSHService setBadge:0];

相关文章

  • iOS远程推送之(五):静默通知

    iOS远程推送之(一):APNs原理和基本配置iOS远程推送之(二):角标applicationIconNumbe...

  • iOS远程推送之(三):点击通知横幅启动应用

    导读 iOS远程推送之(一):APNs原理和基本配置iOS远程推送之(二):角标applicationIconNu...

  • IOS 推送功能

    目录: 1. IOS系统为什么会有推送? 2. 推送的种类; 3. 推送的实现; 4. 第三方推送服务。 1.IO...

  • AppDelegate 分层,实现解耦和瘦身

    一个 iOS 应用可能集成了大量的服务,远程推送、本地推送、生命周期管理、第三方支付、第三方分享....。有没有觉...

  • 自建APNS消息推送服务

    背景 想要给iOS用户推送一些信息,又不想使用极光啊,友盟之类的第三方推送SDK,毕竟是只针对iOS用户的,并且用...

  • iOS第三方之推送

    代码从笔记中摘录,有点老旧 1. 原生推送 JAVA后台 jar 代码片段 2. 极光推送 简介 使用 AppDe...

  • iOS推送通知

    学习iOS开发已经两年多了,推送方面一直使用第三方极光推送,对推送没有进行系统的学习。今天我就把推送相关的知识点梳...

  • iOS消息推送

    关于iOS的推送有很多的第三方可以帮助我们实现,比如说百度推送,极光推送等等。就我使用过的百度推送而言,个人感觉...

  • 使用JPush(极光推送)实现远程通知

    远程推送是APP 必备的功能, 现在第三方的 SDK 已经做的非常完备了, 在 iOS10.0出来之后, 极光推送...

  • iOS 推送通知

    iOS 推送通知 iOS 推送通知

网友评论

    本文标题:iOS第三方之推送

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