JPush--推送

APNs流程:
  1. 到developer.apple.com 去申请开发者资格
  2. 到苹果开发者官网 去申请一个 应用程序的 唯一标识, 即 bundle identify
  3. 凭借这个唯一标识, 可以在官网上申请两个证书.(一个安装在客户端的机器上, 一个是给服务器的)
  4. 当用户手机上的该软件启动之后, (首次)会向用户提出推送申请.
    用户通过申请, 则软件会自动向苹果服务器发出请求, 申请此设备在此应用下的唯一标识. 苹果服务器根据证书来验证是否合法.
  5. 如果验证合法, 则苹果服务器会传递一个deviceToken给此设备. 本质上就是一个32位 16进制 字符串
  6. 你需要把这个字符串 通过 你的服务器给定的接口. 传递过去. 服务器就会进行保存和关联.
  7. 服务器 把要发送给用户的消息+用户的deviceToken+证书 一起提交给苹果服务器
  8. 苹果服务器 根据证书 首先验证是否合法. 合法之后, 通过deviceToken找到对应的设备. 发送消息.
JPush创建应用 --> 获取Appkey

1.上传APNs证书 PS:APNs证书获取流程见2018年iOS APP提交上架流程中4.4
2.JPush上Bundle ID 必须跟项目中info.plist中的一致,否则无法推送

配置工程:

1.导入SDK — > 推荐Cocoapods导入
2.Capabilities —> 开启Application Target的Capabilities —> Push Notifications
3.允许Xcode7及以上支持Http传输方法
选择1:根据域名配置
3.1 Info.plist添加NSAppTransportSecurity(BOOL类型)
3.2 NSAppTransportSecurity添加一个NSExceptionDomains (Dictionary类型)
3.3 把需要支持的域添加给NSExceptionDomains (jpush.cn作为key,类型为Dictionary类型)
3.4 每个域下面需要设置2个属性: NSIncludesSubdomains、NSExceptionAllowsInsecureHTTPLoads (均为BOOL类型,值为YES)
选择2:全局配置
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

初始化设置及功能实现

AppDelegate.h 文件:

#import <JPUSHService.h>

#define JMESSAGE_APPKEY @""

#define CHANNEL @"Publish channel"

@interface AppDelegate : UIResponder <JPUSHRegisterDelegate>

@end

AppDelegate.m 文件:

// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用idfa功能所需要引入的头文件(可选)
#import <AdSupport/AdSupport.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //1.初始化APNs代码
    //Required
    //notice: 3.0.0及以后版本注册可以这样写,也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
//        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    //2.初始化JPush代码
    // Optional
    // 获取IDFA
    // 如需使用IDFA功能请添加此代码并在初始化方法的advertisingIdentifier参数中填写对应值
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];

    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法,改成可上报IDFA,如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容,请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    // channel: 指明应用程序包的下载渠道
    // apsForProduction: 是否用于生产环境
    [JPUSHService setupWithOption:launchOptions appKey:JMESSAGE_APPKEY
                          channel:CHANNEL
                 apsForProduction:YES
            advertisingIdentifier:nil];
    
    //2.1.9版本新增获取registration id block接口。JPush相关事件监听
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功:%@",registrationID);
        }
        else{
            NSLog(@"registrationID获取失败,code:%d",resCode);
        }
    }];

    return YES;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // 3.注册APNs成功并上报DeviceToken
    // Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    
    [JPUSHService resetBadge];
    [application setApplicationIconBadgeNumber:0];

}

//4.处理APNs通知回调方法
#pragma mark- JPUSHRegisterDelegate

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {

    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;

    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];

    }else {
        // 本地通知
    }
    completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert); // 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {

    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;

    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        [self handleNotiMessage:userInfo];//处理消息内容

    }else {
        // 本地通知
    }
    completionHandler();  // 系统要求执行这个方法
}

// iOS 7,8,9 Support
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    [self handleNotiMessage:userInfo];//处理消息内容
    
    completionHandler(UIBackgroundFetchResultNewData);

}

//处理消息内容 根据后台返回数据进行对应处理
- (void) handleNotiMessage:(NSDictionary *)userInfo {
    if (userInfo[@"extrasData"] != nil) {
        NSString *extrasData = userInfo[@"extrasData"];
        NSDictionary *extras = [NSString parseJSONStringToNSDictionary:extrasData];
        NSString *type = [userInfo valueForKey:@"extrasType"];
        if ([type isEqualToString:@"1"]) {
        } else if ([type isEqualToString:@"5"]) {
        }
    }
    
    NSInteger badge = [userInfo[@"aps"][@"badge"] integerValue];
    if (badge == 0) {
        [JPUSHService setBadge:0];
        [UIApplication sharedApplication].applicationIconBadgeNumber=0;
    } else {
        badge --;
        [JPUSHService setBadge:badge];
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:badge];
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

    NSString *alert = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];

    if (application.applicationState == UIApplicationStateActive) {

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"推送消息"
                                                            message:alert
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
        [alertView show];
    }
    
    NSInteger badge = [userInfo[@"aps"][@"badge"] integerValue];
    if (badge == 0) {
        [JPUSHService resetBadge];
        [UIApplication sharedApplication].applicationIconBadgeNumber=0;
    } else {
        badge --;
        [JPUSHService setBadge:badge];
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:badge];
    }
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}

推送消息给指定用户实现 -- > 设置别名alias

用户登录时设置别名
PS:alias不能设置nil或者空字符串@“” 建议设置为用户名

[JPUSHService setAlias:alias completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
    NSInteger ResCode = iResCode;
    NSString *Alias = iAlias;//返回的状态码 0为成功
    NSInteger iSeq = seq;
    NSLog(@"%ld----%@=---%ld",ResCode,Alias,iSeq);
} seq:seq];

用户退出时删除别名

[JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
    NSInteger ResCode = iResCode;
    NSString *Alias = iAlias;//返回的状态码 0为成功
    NSInteger iSeq = seq;
    NSLog(@"%ld----%@=---%ld",ResCode,Alias,iSeq);
} seq:seq];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容