zoukankan      html  css  js  c++  java
  • ios-极光推送sdk使用

    一、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  打开

    四、代码

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

    //
    //  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

    //
    //  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

    #import <Foundation/Foundation.h>
    
    @interface NSString (jmCategory)
    
    + (NSString *)logDic:(NSDictionary *)dic;
    
    @end
    View Code

    NSString+jmCategory.m

    //
    //  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

    //  APIKey.h
    
    #ifndef APIKey_h
    #define APIKey_h
    
    #define JPushKey @"自己项目的极光key"
    
    #endif /* APIKey_h */
    View Code

    AppDelegate.m

    //
    //  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
  • 相关阅读:
    LINUX 新手 入门 教程
    mysql 新手入门 官方文档+官方中文文档附地址
    Git常用命令
    修改dotnet运行.netcore web程序默认端口
    centos7.6下部署.netcore3.1web程序
    supervisor安装及使用(转载)
    linux(CentOS7.6)下安装mysql8.0并使用navicat远程访问
    uni-app为组件uni-icons增加自定义图标(超简单)
    常用正则表达式收录(持续更新)
    CentOS7.6安装SQL SERVER 2017
  • 原文地址:https://www.cnblogs.com/sayimba/p/8341482.html
Copyright © 2011-2022 走看看