iOS开发-云推送详解

来源:互联网 发布:网络兼职项目申请表 编辑:程序博客网 时间:2024/06/08 11:09

一.导入SDK

1.添加到SDK到工程中的步骤如下:

• 将libBPush.a和BPush.h BPushCerResource.bundle添加到自己的工程下,添加时需要注意勾选当前Target

• SDK需要以下库:Foundation.framework、CoreTelephony.framework、libz.dylib、SystemConfiguration.framework,CoreLocation.framework 如果使用了idfa版需要添加AdSupport.framework 在工程中添加。


2.客户端设置开启Remote notifications,需要在Xcode 中修改应用的 Capabilities 开启Remote notifications,(红框内的必须要做哦)请参考下图:



3.客户端需要在工程内添加新的 target(通知扩展) 继承 UNNotificationServiceExtension 



4.导入最基本的代码

#import "AppDelegate.h"

#import "BPush.h"

#import "ViewController.h"

#import "SkipViewController.h"

#ifdef NSFoundationVersionNumber_iOS_9_x_Max

#import <UserNotifications/UserNotifications.h>

#endif

static BOOL isBackGroundActivateApplication;

// rgb颜色转换(16进制->10进制)

#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue &0xFF0000) >>16))/255.0 green:((float)((rgbValue &0xFF00) >>8))/255.0 blue:((float)(rgbValue &0xFF))/255.0 alpha:1.0]


@interface AppDelegate ()<UIAlertViewDelegate>

{

    UITabBarController *_tabBarCtr;

}


@property (nonatomic,strong)ViewController *viewController;


@end


@implementation AppDelegate


#warning

//***********************关于如何设置badge角标加1的方法***********************


/*

 服务端推送的badge是几就会显示几,你只需要跟服务端同步消息数目,然后让服务端自己,该推送几,就推送几,比如你应用打开的时候,或者进入后台的时候跟服务端同步,这个点,需要你们自己去设计,应用没有消息的时候,服务端推送了1,当应用打开时候,告诉服务端,app没点击通知,那下次应用推送2,依次类推。

 */


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

    self.window = [[UIWindowalloc]initWithFrame:[[UIScreenmainScreen]bounds]];

    self.window.backgroundColor = [UIColor whiteColor];

    self.viewController = [[ViewControlleralloc]initWithNibName:@"ViewController"bundle:nil];

    _tabBarCtr = [[UITabBarControlleralloc]init];

    self.window.rootViewController = _tabBarCtr;

    UINavigationController *nav = [[UINavigationControlleralloc]initWithRootViewController:self.viewController];

    // 根视图是nav

    _tabBarCtr.viewControllers =@[nav];

    /*

    // 根视图是普通的viewctr

    _tabBarCtr.viewControllers = @[self.viewController]; */

    [self.windowmakeKeyAndVisible];

    

    UIColor * cc = [UIColorwhiteColor];

    NSDictionary * dict = [NSDictionarydictionaryWithObject:ccforKey:UITextAttributeTextColor];

    nav.navigationBar.titleTextAttributes = dict;

    [nav.navigationBarsetTranslucent:NO];//设置navigationbar的半透明

//    [_tabBarCtr.tabBar setTranslucent:NO];

    if ([[[UIDevicecurrentDevice]systemVersion]floatValue]>=7.0)

    {

        [nav.navigationBarsetBarTintColor:UIColorFromRGB(0x39526d)];

        [_tabBarCtr.tabBarsetBarTintColor:UIColorFromRGB(0x39526d)];

    }

    else

    {

        [nav.navigationBarsetTintColor:UIColorFromRGB(0x39526d)];

        [_tabBarCtr.tabBarsetTintColor:UIColorFromRGB(0x39526d)];

    }

    // iOS10 下需要使用新的 API

    if ([[[UIDevicecurrentDevice]systemVersion]floatValue] >=10.0) {

#ifdef NSFoundationVersionNumber_iOS_9_x_Max

        UNUserNotificationCenter* center = [UNUserNotificationCentercurrentNotificationCenter];

        

        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert +UNAuthorizationOptionSound +UNAuthorizationOptionBadge)

                              completionHandler:^(BOOL granted,NSError * _Nullable error) {

                                  // Enable or disable features based on authorization.

                                  if (granted) {

                                      [application registerForRemoteNotifications];

                                  }

                              }];

#endif

    }

    elseif ([[[UIDevicecurrentDevice]systemVersion]floatValue] >=8.0) {

        UIUserNotificationType myTypes =UIUserNotificationTypeBadge |UIUserNotificationTypeSound |UIUserNotificationTypeAlert;

        

        UIUserNotificationSettings *settings = [UIUserNotificationSettingssettingsForTypes:myTypescategories:nil];

        [[UIApplicationsharedApplication]registerUserNotificationSettings:settings];

    }else {

        UIRemoteNotificationType myTypes =UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound;

        [[UIApplicationsharedApplication]registerForRemoteNotificationTypes:myTypes];

    }


    #warning 测试开发环境时需要修改BPushModeBPushModeDevelopment需要修改Apikey为自己的Apikey

    

    // App启动时注册百度云推送服务,需要提供 Apikey

    

    [BPushregisterChannel:launchOptionsapiKey:@"Apikey为自己的Apikey"pushMode:BPushModeDevelopmentwithFirstAction:@"打开"withSecondAction:@"关闭"withCategory:@"test"useBehaviorTextInput:YESisDebug:YES];

    

    // 禁用地理位置推送需要再绑定接口前调用。

    

    [BPushdisableLbs];

    

    // App 是用户点击推送消息启动

    NSDictionary *userInfo = [launchOptionsobjectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];

    if (userInfo) {

        [BPushhandleNotification:userInfo];

    }

#if TARGET_IPHONE_SIMULATOR

    Byte dt[32] = {0xc6,0x1e,0x5a,0x13,0x2d,0x04,0x83,0x82,0x12,0x4c,0x26,0xcd,0x0c,0x16,0xf6,0x7c,0x74,0x78,0xb3,0x5f,0x6b,0x37,0x0a,0x42,0x4f,0xe7,0x97,0xdc,0x9f,0x3a,0x54,0x10};

    [selfapplication:applicationdidRegisterForRemoteNotificationsWithDeviceToken:[NSDatadataWithBytes:dtlength:32]];

#endif

    //角标清0

    [[UIApplicationsharedApplication]setApplicationIconBadgeNumber:0];

    /*

     // 测试本地通知

    [self performSelector:@selector(testLocalNotifi) withObject:nil afterDelay:1.0];

    */

    returnYES;

}


- (void)testLocalNotifi

{

    NSLog(@"测试本地通知啦!!!");

    NSDate *fireDate = [[NSDatenew]dateByAddingTimeInterval:5];

    [BPushlocalNotification:fireDatealertBody:@"这是本地通知"badge:3withFirstAction:@"打开"withSecondAction:niluserInfo:nilsoundName:nilregion:nilregionTriggersOnce:YEScategory:niluseBehaviorTextInput:YES];

}


// 此方法是用户点击了通知,应用在前台或者开启后台并且应用在后台时调起

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler

{

     completionHandler(UIBackgroundFetchResultNewData);

    // 打印到日志 textView

    NSLog(@"********** iOS7.0之后 background **********");

    // 应用在前台,不跳转页面,让用户选择。

    if (application.applicationState ==UIApplicationStateActive) {

        NSLog(@"acitve ");

        UIAlertView *alertView =[[UIAlertViewalloc]initWithTitle:@"收到一条消息"message:userInfo[@"aps"][@"alert"]delegate:selfcancelButtonTitle:@"取消"otherButtonTitles:@"确定",nil];

        [alertView show];

    }

    //杀死状态下,直接跳转到跳转页面。

    if (application.applicationState ==UIApplicationStateInactive && !isBackGroundActivateApplication)

    {

        SkipViewController *skipCtr = [[SkipViewControlleralloc]init];

        // 根视图是navpush方式跳转

        [_tabBarCtr.selectedViewControllerpushViewController:skipCtranimated:YES];

        NSLog(@"applacation is unactive ===== %@",userInfo);

        /*

        // 根视图是普通的viewctrpresent跳转

        [_tabBarCtr.selectedViewController presentViewController:skipCtr animated:YES completion:nil]; */

    }

    // 应用在后台。当后台设置aps字段里的 content-available值为 1并开启远程通知激活应用的选项

    if (application.applicationState ==UIApplicationStateBackground) {

        NSLog(@"background is Activated Application ");

        // 此处可以选择激活应用提前下载邮件图片等内容。

        isBackGroundActivateApplication =YES;

//        UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:@"收到一条消息" message:userInfo[@"aps"][@"alert"] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];

//        [alertView show];

    }

    [self.viewControlleraddLogString:[NSStringstringWithFormat:@"Received Remote Notification :\n%@",userInfo]];

    

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

}


// iOS8系统中,还需要添加这个方法。通过新的 API注册推送服务

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings

{


    [application registerForRemoteNotifications];

    


}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken

{

    NSLog(@"test:%@",deviceToken);

    [BPushregisterDeviceToken:deviceToken];

    [BPushbindChannelWithCompleteHandler:^(id result,NSError *error) {

        [self.viewControlleraddLogString:[NSStringstringWithFormat:@"Method: %@\n%@",BPushRequestMethodBind,result]];

        // 需要在绑定成功后进行 settag listtag deletetag unbind操作否则会失败

        

        // 网络错误

        if (error) {

            return ;

        }

        if (result) {

            // 确认绑定成功

            if ([result[@"error_code"]intValue]!=0) {

                return;

            }

            // 获取channel_id

            NSString *myChannel_id = [BPushgetChannelId];

            NSLog(@"==%@",myChannel_id);

            

            [BPushlistTagsWithCompleteHandler:^(id result,NSError *error) {

                if (result) {

                    NSLog(@"result ============== %@",result);

                }

            }];

            [BPushsetTag:@"Mytag"withCompleteHandler:^(id result,NSError *error) {

                if (result) {

                    NSLog(@"设置tag成功");

                }

            }];

        }

    }];

    

    // 打印到日志 textView

    [self.viewControlleraddLogString:[NSStringstringWithFormat:@"Register use deviceToken : %@",deviceToken]];

    


}


// DeviceToken获取失败时,系统会回调此方法

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error

{

    NSLog(@"DeviceToken获取失败,原因:%@",error);

}


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

{

    // App 收到推送的通知

    [BPushhandleNotification:userInfo];

    NSLog(@"********** ios7.0之前 **********");

    // 应用在前台或者后台开启状态下,不跳转页面,让用户选择。

    if (application.applicationState ==UIApplicationStateActive || application.applicationState ==UIApplicationStateBackground) {

        NSLog(@"acitve or background");

        UIAlertView *alertView =[[UIAlertViewalloc]initWithTitle:@"收到一条消息"message:userInfo[@"aps"][@"alert"]delegate:selfcancelButtonTitle:@"取消"otherButtonTitles:@"确定",nil];

        [alertView show];

    }

    else//杀死状态下,直接跳转到跳转页面。

    {

        SkipViewController *skipCtr = [[SkipViewControlleralloc]init];

        [_tabBarCtr.selectedViewControllerpushViewController:skipCtranimated:YES];

    }


    [self.viewControlleraddLogString:[NSStringstringWithFormat:@"Received Remote Notification :\n%@",userInfo]];

    

    NSLog(@"%@",userInfo);

}


- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification

{

    NSLog(@"接收本地通知啦!!!");

    [BPushshowLocalNotificationAtFront:notificationidentifierKey:nil];

}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{

    if (buttonIndex ==1) {

        SkipViewController *skipCtr = [[SkipViewControlleralloc]init];

        // 根视图是navpush方式跳转

        [_tabBarCtr.selectedViewControllerpushViewController:skipCtranimated:YES];

        /*

         // 根视图是普通的viewctrpresent跳转

         [_tabBarCtr.selectedViewController presentViewController:skipCtr animated:YES completion:nil]; */

    }

}





二.iOS证书问题

在 iOS App 中加入消息推送功能时,必须要在 Apple 的开发者中心网站上申请推送证书,每一个 App 需要申请两个证书,一个在开发测试环境下使用,另一个用于上线到 AppStore 后的生产环境。

1.创建App IDs(第一次建项目,如果在原有的项目上增加的百度云功能,可看注释)

(1)在进入证书界面后,在左边的Identifiers选择中选定App IDs,点右上角加号创建Appid,如下图:


(2)在创建 App ID 的过程中,过程如下图

        name—>为显示内容,自己利于分辨,如下图:



boundle ID —> 为项目的boundle ID,如下图:



在创建 App ID 的过程中,需要勾选 Push 服务,如下图:



*************注释:(如果在原有的项目上增加的百度云功能介绍)

*********(1)这是我原有的所有App IDs,找到项目的IDs,点击,如下图



**********(2)选择按钮,再次点击Edit编辑按钮,如下图。(正常情况下,红色原点区域为置灰状态,不是绿色状态,因为此项目是我整理好的项目)



***********(3)进入编辑状态,勾选push Notifications。如下图:



*********勾选之后返回看push Notifications这个选项应该是黄色。(因为push服务处于configurable状态),如下图


(3)然后配置好对应的推送环境,个人版和企业版的开发环境都是选择创建Development SSL Certificate类型的。个人版和企业版的发布环境。发布环境分以下三种:1. in-house必须是企业开发账户(企业内)(299美金) 2.ad-hoc个人账户或公司Company账户(99美金),但只用于内部测试(总共100个设备).3.上线Appstore只能是个人账户或公司Company账户(99美金))如下图:



2.创建证书,直接点击Create certificate(以开发证书为例)

(1)点击 Create Certificate按钮后会出现“About Creating a Certificate Signing Request (CSR)”,如下图:


(2)到了这里,需要停下制作 CSR 文件,制作过程比较简单,下面是制作的过程。打开 Mac 系统软件'钥匙串访问',选择 '证书助理' 及 '从证书颁发机构请求证书',制作 CSR 文件,如下图:





(3)生成证书后,返回到 “About Creating a Certificate Signing Request (CSR)” 的界面,点击 continue,然后在 “Choose File” 选择生成的CSR文件,最后点击 Generate,生成证书。

在证书制作已经完成。下载并双击用“钥匙串访问” 程序打开后,在左边一栏,上面选择登录,下面选择证书,然后选择刚刚打开的证书,切记不要展开它,直接右击导出p12,如下图:



最后进入终端,到证书目录下,运行以下命令将p12文件转换为pem证书文件:

cd 项目目录

openssl pkcs12 -in baiduCert.p12 -out baiduCert.pem -nodes

(创建P12证书,是为了在创建应用时使用,需要导入P12开发证书和发布证书)


3.Provisioning Profile的创建

(1) 点击下图的+按钮开始创建profile,如下图:





(2)选择创建profile的appid和开发者证书,并选择设备(刚才自己创建的App IDs),最后生成profile。如下图:



(3)选择你要的证书,和设备,如下图:





(4)最后下载profile配置到Xcode中进行开发测试

     下载之后,打开Xcode项目,双击profile





0 0