iOS开发-百度云推送环境搭建

一.导入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]; */

    }

}



****************************开发环境基本搭建完毕****************************

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值