ios-极光推送sdk使用

摘要:
1、 SDK导入选项1:Cocoapods导入pod“JPush”选项2:手动导入1.在Aurora官方网站上下载最新的SDK 2.解压压缩包并将Lib下的所有文件复制到项目3.添加相关框架以依赖CFNetwork.frameworkCoreFoundation.frameworkCore电话.frameworkSystemConfiguration.frameworkCoreGraph

一、SDK导入

选择1:Cocoapods导入
pod 'JPush'

选择2:手动导入
1、在极光官网下载最新SDK
2、解压压缩包,将Lib下的所有文件复制到工程中
3、增加相关的framework依赖
    CFNetwork.framework
    CoreFoundation.framework
    CoreTelephony.framework
    SystemConfiguration.framework
    CoreGraphics.framework
    Foundation.framework
    UIKit.framework
    Security.framework
    libz.tbd (Xcode7以下版本是libz.dylib)
    AdSupport.framework (获取IDFA需要;如果不使用IDFA,请不要添加)
    UserNotifications.framework (Xcode8及以上)
    libresolv.tbd (JPush 2.2.0及以上版本需要, Xcode7以下版本是libresolv.dylib)

二、创建 推送证书并将推送证书上传极光后台管理

三、TARGETS->Capabilities->Push Notifications  打开

四、代码

ios-极光推送sdk使用第1张

TRJPushHelper.h  极光推送相关API封装

ios-极光推送sdk使用第2张ios-极光推送sdk使用第3张
//
//  TRJPushHelper.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

/*
 * @brief 极光推送相关API封装
 *
 */
@interface TRJPushHelper : NSObject
/**
 *
 *  在应用启动的时候调用
 *
 ***/
+ (void)setupWithOptions:(NSDictionary *)launchOptions;

- (void)setupWithOptions:(NSDictionary *)launchOptions uuidString:(NSString *)uuidString;
/**
 *
 *  在AppDelegate注册设备处调用
 *
 ***/
+ (void)registerDeviceToken:(NSData *)deviceToken;
/**
 *
 * iOS7以后,才有Completion,否则传nil
 *
 ***/
+ (void)handleRemoteNotification:(NSDictionary *)userInfo completion:(void (^)(UIBackgroundFetchResult))completion;
/**
 *
 * 显示本地通知在最前面
 *
 ***/
+ (void)showLocalNotificationAtFront:(UILocalNotification *)notification;

/**
 *
 * 上传别名到极光推送
 *
 ***/
+ (void)uploadToJpushAlias:(NSString *)alias andToServier:(BOOL)isServer;

+ (void)uploadToServerAlias:(NSString *)alias push_status:(NSString *)push_status;

+ (TRJPushHelper *)sharedHelper;

@end
View Code

TRJPushHelper.m

ios-极光推送sdk使用第4张ios-极光推送sdk使用第5张
//
//  TRJPushHelper.m

#import "TRJPushHelper.h"
//自己封装的转换
#import "NSString+jmCategory.h"
//极光自己的
#import "JPUSHService.h"

//极光项目的key
#import "APIKey.h" 
#import <AdSupport/ASIdentifierManager.h>

#ifdef NSFoundationVersionNumber_iOS_9_x_Max

#import <UserNotifications/UserNotifications.h>

#endif

@interface TRJPushHelper ()<JPUSHRegisterDelegate>


@end
static TRJPushHelper *sharedHelper = nil;
@implementation TRJPushHelper
+ (TRJPushHelper *)sharedHelper {
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        sharedHelper = [[TRJPushHelper alloc] init];
    });
    
    return sharedHelper;

}
+ (void)setupWithOptions:(NSDictionary *)launchOptions
{
    // Required
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
    // ios8之后可以自定义category
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0)
    {
        // 可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
#if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_8_0
        // ios8之前 categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
#endif
    }
#else
    // categories 必须为nil
    [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                      UIRemoteNotificationTypeSound |
                                                      UIRemoteNotificationTypeAlert)
                                          categories:nil];
#endif
    
    //Required
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容,请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    
    
    [JPUSHService setupWithOption:launchOptions appKey:JPushKey
                          channel:@"App Store"
                 apsForProduction:YES
            advertisingIdentifier:nil];
    
    //[JPUSHService setupWithOption:launchOptions]; 弃用
    
    
    return;
}

///第一步
- (void)setupWithOptions:(NSDictionary *)launchOptions uuidString:(NSString *)uuidString
{
    // Required
    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
    }
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
    // ios8之后可以自定义category
     else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0)
    {
        // 可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                       UIUserNotificationTypeSound |
                                                       UIUserNotificationTypeAlert)
                                           categories:nil];
    }
    else
    {
#if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_8_0
        // ios8之前 categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                       UIRemoteNotificationTypeSound |
                                                       UIRemoteNotificationTypeAlert)
                                           categories:nil];
#endif
    }
#else
    // categories 必须为nil
    [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                   UIRemoteNotificationTypeSound |
                                                   UIRemoteNotificationTypeAlert)
                                       categories:nil];
#endif
    
    //Required
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容,请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:JPushKey
                          channel:@"App Store"
                 apsForProduction:YES
            advertisingIdentifier:nil];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [JPUSHService setTags:nil alias:@"test" fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
            NSLog(@"rescode: %d, 
tags: %@, 
alias: %@
", iResCode, iTags, iAlias);
            
        }];
    });
    
    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功:%@",registrationID);
            
            NSString *strUrl = [uuidString stringByReplacingOccurrencesOfString:@"-" withString:@""];
            
            NSLog(@"uuidString:%@",strUrl);
            
            [JPUSHService setAlias:strUrl  callbackSelector:nil object:nil];
        }//7C3129208DB44A399BDCAEF0729AA780
        else
        {
            NSLog(@"registrationID获取失败,code:%d",resCode);
        }
    }];
    return;
}

+ (void)registerDeviceToken:(NSData *)deviceToken
{
    [JPUSHService registerDeviceToken:deviceToken];
    return;
}



+ (void)handleRemoteNotification:(NSDictionary *)userInfo completion:(void (^)(UIBackgroundFetchResult))completion {
    [JPUSHService handleRemoteNotification:userInfo];
    
    if (completion)
    {
        completion(UIBackgroundFetchResultNewData);
    }
    return;
}

+ (void)showLocalNotificationAtFront:(UILocalNotification *)notification
{
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
    return;  
}

+ (void)uploadToJpushAlias:(NSString *)alias andToServier:(BOOL)isServer;
{
    [JPUSHService setTags:nil alias:alias fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias)
    {
        
        NSLog(@"[向] -> [JPush] -> [上传] -> [别名] -> [成功]! —> [返回结果 = %zi] 
 [iTags = %@] 
 [别名Alias =%@ ]
", iResCode, iTags, iAlias);
    }];
}

+ (void)uploadToServerAlias:(NSString *)alias push_status:(NSString *)push_status;
{
    NSMutableDictionary *dic_M = [[NSMutableDictionary alloc] init];
    
    [dic_M setValue:@(30) forKey:@"CODE"];
    
    [dic_M setValue:alias forKey:@"alias"];
    
    [dic_M setValue:push_status forKey:@"push_status"];
 
    
}



#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    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([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 前台收到远程通知:%@", [NSString logDic:userInfo]);
        
        //        [rootViewController addNotificationCount];
        
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 前台收到本地通知:{
body:%@,
title:%@,
subtitle:%@,
badge:%@,
sound:%@,
userInfo:%@
}",body,title,subtitle,badge,sound,userInfo);
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以设置
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    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 收到远程通知:%@", [NSString logDic:userInfo]);
      
        
        
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 收到本地通知:{
body:%@,
title:%@,
subtitle:%@,
badge:%@,
sound:%@,
userInfo:%@
}",body,title,subtitle,badge,sound,userInfo);
    }
    
    completionHandler();  // 系统要求执行这个方法
}
#endif


@end
View Code

NSString+jmCategory.h

ios-极光推送sdk使用第6张ios-极光推送sdk使用第7张
#import <Foundation/Foundation.h>

@interface NSString (jmCategory)

+ (NSString *)logDic:(NSDictionary *)dic;

@end
View Code

NSString+jmCategory.m

ios-极光推送sdk使用第8张ios-极光推送sdk使用第9张
//
//  NSString+jmCategory.m

#import "NSString+jmCategory.h"

@implementation NSString (jmCategory)

+ (NSString *)logDic:(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];
    

    return str;
}
@end
View Code

APIKey.h

ios-极光推送sdk使用第10张ios-极光推送sdk使用第11张
//  APIKey.h

#ifndef APIKey_h
#define APIKey_h

#define JPushKey @"自己项目的极光key"

#endif /* APIKey_h */
View Code

AppDelegate.m

ios-极光推送sdk使用第12张ios-极光推送sdk使用第13张
//
//  AppDelegate.m
//  noticeTest

#import "AppDelegate.h"
#import "TRJPushHelper.h"
#import "ViewController.h"
@interface AppDelegate ()
{
    NSString *_uuidString;

}
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
    ViewController * view = [[ViewController alloc]init];
    
    self.window.rootViewController = view;
    [self.window makeKeyAndVisible];

    
    [[TRJPushHelper sharedHelper]  setupWithOptions:launchOptions
                                         uuidString:_uuidString];


    
    return YES;
}

- (void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias {
    
    NSLog(@"rescode: %d, 
tags: %@, 
alias: %@
", iResCode, tags , alias);
    
}

#pragma mark -
#pragma mark -  ************* JUPush *************
#pragma mark -

#pragma mark - 即将根据DeviceToken注册远程通知
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [TRJPushHelper registerDeviceToken:deviceToken];
}


#pragma mark - 即将接收到的通知 (iOS10 弃用)
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [TRJPushHelper handleRemoteNotification:userInfo completion:nil];

    NSLog(@"%@",userInfo);
    
}


#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    ///ios7.0以后才有此功能
    [TRJPushHelper handleRemoteNotification:userInfo completion:completionHandler];
    
    NSLog(@"userInfo-->%@
", userInfo);
    // 应用正处理前台状态下,不会收到推送消息,因此在此处需要额外处理一下
    if (application.applicationState == UIApplicationStateActive)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"收到推送消息"
                                                        message:userInfo[@"aps"][@"alert"]
                                                       delegate:nil
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"确定", nil];
        [alert show];
    }
    return;
}

#endif
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    [TRJPushHelper showLocalNotificationAtFront:notification];
    return;
}


#pragma mark - 通知异常
- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}


@end
View Code

免责声明:文章转载自《ios-极光推送sdk使用》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇asp.net mvc4使用log4.net 日志功能ManualResetEvent 与 AutoResetEvent 的理解和使用下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

iOS:文件归档和解归档的详解和使用

文件归档和解归档: 用途: 所谓文件归档,就是把需要存储的对象数据存储到沙盒的Documents目录下的文件中,即存储到了磁盘上,实现数据的持久性存储和备份。解归档,就是从磁盘上读取该文件下的数据,用来完成用户的需求。对象归档是将对象归档以文件的形式保存到磁盘中(也称为序列化,持久化),使用的时候读取该文件的保存路径的读取文件的内容(也称为接档,反序列化...

iOS 拼接字符串

NSString  *str1=@"我爱"; NSString *str2=@"祖国"; (1)  NSString *all= [NSString stringWithFormat:@"%@>%@",str1,str2];    (2)  NSString *all2= [type stringByAppendingString:subtype];...

iOS开发经验总结(上)

在iOS开发中经常需要使用的或不常用的知识点的总结,几年的收藏和积累(踩过的坑)。 一、 iPhone Size 手机型号 屏幕尺寸 iPhone 4 4s 320 * 480 iPhone 5 5s 320 * 568 iPhone 6 6s 375 * 667 iphone 6 plus 6s plus 414 *...

iOS 测试 | iOS 自动化性能采集

​今天小编跟大家分享一篇来自学院内部学员的技术分享,本文主要介绍了作者在进行 iOS 自动化性能采集的一些经验,希望对大家在进行 iOS 自动化测试时有一些启发。 不要为小事遮住视线,我们还有更大的世界 前言 对于iOS总体生态是比较封闭的,相比Android没有像adb这种可以查看内存、cpu的命令.在日常做性能测试,需要借助xcode中instrum...

ES笔记四:索引操作

一. index 1. 命名规则 _index 命名必须小写,不能以下划线开头,不能包含逗号、 _type 命名可以是大写或者小写,但是不能以下划线或者句号开头,不应该包含逗号, 并且长度限制为256个字符、 _id 唯一确定的文档,要么提供自己的_id ,要么es会自动生成 2.创建索引 如果你想禁止自动创建索引,在elasticse...

重构的技巧

原文:http://www.cocoachina.com/industry/20140816/9397.html 我想一条童子军的军规:“始终保持露营地比你发现它的时候还要干净”。如果你在地上发现了一点脏东西,不管是谁弄的,都清理掉它。要为了下一拨来露营的人改善环境。(实际上,那条规矩的早期版本,出自Robert Stephenson Smyth Bden...