推送的 代码实战写法

推送的设置

 

/*

 launchOptions   为NSDictionary类型的对象,里面存储有此程序启动的原因

 

1.若用户直接启动,lauchOptions内无数据;

2.若由其他应用程序通过openURL:启动,则UIApplicationLaunchOptionsURLKey对应的对象为启动URL(NSURL,UIApplicationLaunchOptionsSourceApplicationKey对应启动的源应用程序的bundle ID (NSString);

3.若由本地通知启动,则UIApplicationLaunchOptionsLocalNotificationKey对应的是为启动应用程序的的本地通知对象(UILocalNotification);

4.若由远程通知启动,则UIApplicationLaunchOptionsRemoteNotificationKey对应的是启动应用程序的的远程通知信息userInfo(NSDictionary);

其他key还有UIApplicationLaunchOptionsAnnotationKey,UIApplicationLaunchOptionsLocationKey,

 UIApplicationLaunchOptionsNewsstandDownloadsKey。

 

 若要使用远程推送,满足两个条件:

 一、用户需 要调用注册用户推送registerUserNotificationSettings;

 二、在info.plist文件中UIBackgroundModes必须包含远程通知。

 当App进入到后台时,可以有一段时间做处理工作。对于长时间运行的任务,需要在Info.plist添加一行,键为UIBackgroundModes,值为一个数组

 */

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

{

      _pushArray = [[NSMutableArray alloc] init];  //接受远程推送消息的列表

      if (launchOptions != nil)

    {

        DLog(@"LUN:%@", launchOptions);

        // UIApplicationLaunchOptionsRemoteNotificationKey 这个key值就是push的信息

        NSDictionary *dic = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];

        DLog(@"LUN:%@", dic);

        // 为了复用代码,统一到下面这个处理方法中handlePushNotify.

        

        if([dic objectForKey:@"pushType"] != nil)

        {

            if ([[dic objectForKey:@"pushType"]intValue] ==1 || [[dic objectForKey:@"pushType"]intValue] == 2)

            {

                [WCAlertView showAlertWithTitle:@"标题"

                                        message:[[dic objectForKey:@"aps"] objectForKey:@"alert"]

                             customizationBlock:^(WCAlertView *alertView) {

                                 

                             } completionBlock:^(NSUInteger buttonIndex, WCAlertView *alertView) {

                                 

                             } cancelButtonTitle:@"确定" otherButtonTitles: nil];

            }else

            {

                [[YFGlobalVariables sharedInstance].pushMesArray addObject:dic];

                [_pushArray addObject:dic];

            }

        }

    }

 

 

/*

     iOS8拥有了全新的通知中心,有全新的通知机制

     

     当屏幕顶部收到推送时只需要往下拉,就能看到快速操作界面,并不需要进入该应用才能操作。在锁屏界面,对于推送项目也可以快速处理。

     基本上就是让用户尽量在不离开当前页面的前提下处理推送信息,再次提高处理效率。

     能够进行直接互动的短信、邮件、日历、提醒,第三方应用,可以让你不用进入程序就能进行快捷操作,并专注于手中正在做的事情。

     */

    

    /*

     我们需要注意这个UIUserNotificationActionContextDefault,如果我们使用这个,我们会得到这个推送行为,Maybe和Accept

     我们还可以使用UIUserNotificationActionContextMinimal得到的是Decline和Accept行为

     */

       

    if ([getSystemVersion() floatValue] >= 8.0) {

        //这里主要是针对iOS 8.0,相应的8.1,8.2等版本各程序员可自行发挥,如果苹果以后推出更高版本还不会使用这个注册方式就不得而知了……

        UIMutableUserNotificationAction *action = [[UIMutableUserNotificationAction alloc] init];

        action.identifier = @"action";//按钮的标示

        action.title=@"Accept";//按钮的标题

        action.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序

        //    action.authenticationRequired = YES;

        //    action.destructive = YES;

        

        UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];

        action2.identifier = @"action2";

        action2.title=@"Reject";

        action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序,在后台处理

        

        action.authenticationRequired = YES;//需要解锁才能处理,如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略;

        action.destructive = YES;

        

        //2.创建动作(按钮)的类别集合

        UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init];

        categorys.identifier = @"alert";//这组动作的唯一标示,推送通知的时候也是根据这个来区分

        [categorys setActions:@[action,action2] forContext:(UIUserNotificationActionContextMinimal)];

        

        //3.创建UIUserNotificationSettings,并设置消息的显示类类型

        /*+ (instancetype)settingsForTypes:(UIUserNotificationType)types   categories:(NSSet *)categories;

         * 1.参数:推送类型

         * 2.参数:推送 categories 集合

         */

        UIUserNotificationSettings *notiSettings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge |

                                                                                                 UIUserNotificationTypeAlert |

                                                                                                 UIRemoteNotificationTypeSound)

                                                                                     categories:[NSSet setWithObjects:categorys, nil]];

        [application registerUserNotificationSettings:notiSettings];

    }else

    {

        UIRemoteNotificationType types =(UIRemoteNotificationTypeBadge

                                         |UIRemoteNotificationTypeSound

                                         |UIRemoteNotificationTypeAlert);

        [[UIApplication sharedApplication]  registerForRemoteNotificationTypes:types];

    }

    //消息推送支持的类型,注册消息推送

}

 

 

 

 

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url

  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation

{

    if ([sourceApplication isEqualToString:@"com.meiYa.shineTour"])

    {

        

        return YES;

    }

    else

        return NO;

}

 

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url

{

    if (!url)

    {

        return NO;

    }

    

    return YES;

}

 

#pragma mark --处理推送

 

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

{

    //成功注册registerUserNotificationSettings:后,回调的方法 iOS8

    [application registerForRemoteNotifications];

}

 

//这里输出的DeviceToken为尖括号括起来的一串数字,是NSData类型。

 

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

{

    DLog(@"获取DeviceToken成功: {%@}",deviceToken);

    NSString *token = [NSString stringWithFormat:@"%@", deviceToken];

#if 1

    [YFGlobalVariables sharedInstance].deviceID = [[token substringWithRange:NSMakeRange(1, token.length-2)]

                                                   stringByReplacingOccurrencesOfString:@" "

                                                   withString:@""];

#elif 0

     [YFGlobalVariables sharedInstance].deviceID = [[[[token description]

                             stringByReplacingOccurrencesOfString:@"<" withString:@""]

                            stringByReplacingOccurrencesOfString:@">" withString:@""]

                           stringByReplacingOccurrencesOfString:@" " withString:@""] ;

#endif

}

 

- (void)application:(UIApplication *)application

didFailToRegisterForRemoteNotificationsWithError:(NSError *)error

{

    DLog(@"注册消息推送失败,Register Remote Notifications error:{%@}",[error localizedDescription]);

}

 

- (void)application:(UIApplication *)application

didReceiveRemoteNotification:(NSDictionary *)userInfo

{

    // 处理推送消息

    DLog(@"处理收到的远程消息推送,userinfo:%@",userInfo);

    DLog(@"收到推送消息:%@",[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]);

    

    if ([[userInfo objectForKey:@"pushType"]intValue] ==1 || [[userInfo objectForKey:@"pushType"]intValue] == 2)

    {

        [[YFGlobalVariables sharedInstance].pushMesArray addObject:userInfo];

        

        [_pushArray addObject:userInfo];

        

        [WCAlertView showAlertWithTitle:@"标题"

                                message:[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]

                     customizationBlock:^(WCAlertView *alertView) {

                         

                     } completionBlock:^(NSUInteger buttonIndex, WCAlertView *alertView) {

                         if (buttonIndex == 1) {

                             [self checkNotificationMessage];

                         }

                         else

                         {

                             [self.pushArray removeLastObject];

                         }

                         

                     } cancelButtonTitle:@"取消" otherButtonTitles:@"查看", nil];

        

    }

    else

    {

        [WCAlertView showAlertWithTitle:@"标题"

                                message:[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]

                     customizationBlock:^(WCAlertView *alertView) {

                         

                     } completionBlock:^(NSUInteger buttonIndex, WCAlertView *alertView) {

                         

                     } cancelButtonTitle:@"确定" otherButtonTitles: nil];

    }

    

    

}

 

 

#pragma mark - 推送消息的规则判断

// 根据 信息 跳转到 对应的界面 中  YFIndexViewController为首页的界面 视图控制器

/*

 

*/

- (void)checkNotificationMessage

{

    YFIndexViewController *viewControllers =  [[self.tabbarController viewControllers] objectAtIndex:0];

    [viewControllers pushNotficationViewController];

}

 

//YFIndexViewController中的方法 pushNotficationViewController

//#define kAppDelegate        ((YFAppDelegate *)[UIApplication sharedApplication].delegate)

-(void)pushNotficationViewController

{

    if (kAppDelegate.pushArray.count > 0) {

        if ([NSString emptyOrNull:[YFGlobalVariables sharedInstance].userInfoModel.userID]) {

            [self showLoginView];

        }

        else

        {

            [self pushMessageCheck];

        }

    }

}

 

 

- (void)pushMessageCheck

{

    if (kAppDelegate.pushArray.count > 0) {

        

        NSMutableDictionary *userDictionary = [YFFileManager readUserLoginDefaultWithName:@"userLogin"];

        

        NSDictionary *dic = [kAppDelegate.pushArray lastObject];

 

        NSString *userName =[dic objectForKey:@"userName"];

        if ([userName isEqualToString:[userDictionary objectForKey:@"userName"]]) {

            

            if ([[[getAppDelegate().pushArray lastObject] objectForKey:@"pushType"]intValue]==2)

            {

                [YFGlobalVariables sharedInstance].isLowPricePush = YES;

                [self getCurrentUserInfo];

                

            }else

            {

                if (getAppDelegate().pushArray.count != 0)

                {

                    NSDictionary *dictionary =[[NSDictionary alloc] initWithDictionary:[getAppDelegate().pushArray lastObject]];

                    [self lookForOrderDetail:[dictionary objectForKey:@"orderNo"] orderType:[[dictionary objectForKey:@"orderType"] integerValue]];

                }

            }

        }

        else

        {

            [kAppDelegate.tabbarController selectTabAtItem:YFTabBarIndexItem];

            [YFUtil accoutLogout];

            NSMutableDictionary *loginDic = [[NSMutableDictionary alloc] init];

            [loginDic setObject:userName forKey:@"userName"];

            [loginDic setObject:@"" forKey:@"userPassword"];

            [loginDic setObject:[NSNumber numberWithBool:NO] forKey:@"isAutoLogin"];

            [YFFileManager saveUserLoginDefaultsDataWithName:@"userLogin" saveObject:loginDic];

             [self showLoginView];

        }

    }

}

 

//审批推送时的跳转

-(void)lookForOrderDetail:(NSString*)orderString orderType:(NSInteger)orderType;

{

    //[self showLoadWaitView];

    

    if (orderType == 1) {

        YFAirOrderDetailViewController *airOrderController = [[YFAirOrderDetailViewController alloc] initWithOrderNo:orderString];

        [self.navigationController pushViewController:airOrderController animated:YES];

    }

    else if(orderType == 2)

    {

        YFChangeOrderDetailViewController *changeDetailController = [[YFChangeOrderDetailViewController alloc] initWithOrderInfo:orderString];

        [self.navigationController pushViewController:changeDetailController animated:YES];

    }

    else if(orderType == 3)

    {

        YFReturnOrderDetailViewController *returnOrderController = [[YFReturnOrderDetailViewController alloc] initWithOrderInfo:orderString];

        [self.navigationController pushViewController:returnOrderController animated:YES];

    }

    else if(orderType == 5)

    {

        YFHotelOrderDetailViewController *hotelViewController = [[YFHotelOrderDetailViewController alloc] init];

        hotelViewController.orderNo = orderString;

        [self.navigationController pushViewController:hotelViewController animated:YES];

    }

    else if(orderType == 70)

    {

        YFTrainOrderDetailViewController *orderDetailController = [[YFTrainOrderDetailViewController alloc] init];

        orderDetailController.orderNo = orderString;

        [self.navigationController pushViewController:orderDetailController animated:YES];

        

    }else if(orderType == 80)

    {

        YFTrainReturnTicketViewController *returnOrderDetailController  = [[YFTrainReturnTicketViewController alloc] init];

        returnOrderDetailController.orderNo = orderString;

        [self.navigationController pushViewController:returnOrderDetailController animated:YES];

    }

    

}

 

 

 

最后 :手把手教你 iOS推送 

http://www.cocoachina.com/industry/20130321/5862.html

posted @ 2015-09-06 16:47  heyuan123  阅读(383)  评论(0编辑  收藏  举报