【原】 ios點擊推送消息跳轉到指定界面

這里只粘貼了代碼中重要跳轉頁面部分代碼及當用戶在瀏覽app的時候彈出消息提示(自定義彈出框)

// 推送收到推送消息
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // IOS 7 Support Required
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"收到通知:%@", [self logDic:userInfo]);

    //判斷app是不是在前臺運行,有三個狀態(如果不進行判斷處理,當你的app在前臺運行時,收到推送時,通知欄不會彈出提示的)
    // UIApplicationStateActive, 在前臺運行
    // UIApplicationStateInactive,未啟動app
    //UIApplicationStateBackground    app在后臺

    NSInteger badge=[userInfo[@"aps"][@"badge"] integerValue ];
    [[NSUserDefaults standardUserDefaults]setInteger:badge forKey:@"MesNum"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeNameNotification" object:self userInfo:@{@"name":@(badge)}];

    NSLog(@"角標:%ld",badge);
    if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
    {  //此時app在前臺運行,我的做法是彈出一個alert,告訴用戶有一條推送,用戶可以選擇查看或者忽略,自定義彈出框


        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];

        msg=userInfo;
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        UIView *bgView=[[UIView alloc]initWithFrame:CGRectMake(0, 0,screen_width, 65)];
        bgView.backgroundColor=[UIColor blackColor];
        [window addSubview:bgView];

        UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(ClickTap:)];
        [bgView addGestureRecognizer:tap];

        UIImageView *iconImv=[[UIImageView alloc]initWithFrame:CGRectMake(15, 5,18, 18)];
        iconImv.backgroundColor=[UIColor clearColor];
        iconImv.layer.cornerRadius=3;
        iconImv.layer.masksToBounds=YES;
        NSDictionary *infoPlist = [[NSBundle mainBundle] infoDictionary];
        NSString *icon = [[infoPlist valueForKeyPath:@"CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles"] lastObject];
        iconImv.image=[UIImage imageNamed:icon];
        [bgView addSubview:iconImv];
        UILabel *titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(iconImv.frame)+7.5, CGRectGetMinY(iconImv.frame), 60, CGRectGetHeight(iconImv.frame))];
        titleLabel.backgroundColor=[UIColor clearColor];
        titleLabel.text=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
        titleLabel.textColor=[UIColor whiteColor];
        titleLabel.font=[UIFont boldSystemFontOfSize:12];
        [bgView addSubview:titleLabel];
        UILabel *timeLabel=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(titleLabel.frame)+2.5, CGRectGetMinY(iconImv.frame), 100, CGRectGetHeight(iconImv.frame))];
        timeLabel.backgroundColor=[UIColor clearColor];
        timeLabel.textAlignment=NSTextAlignmentLeft;
        timeLabel.text=@"現在";
        timeLabel.textColor=[UIColor colorWithRed:0.402 green:0.478 blue:1.000 alpha:1.000];
        timeLabel.font=[UIFont boldSystemFontOfSize:10];
        [bgView addSubview:timeLabel];
        UILabel *alertLabel=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(iconImv.frame)+7.5, CGRectGetMinY(titleLabel.frame)+7.5, screen_width-CGRectGetMaxX(iconImv.frame)-15, CGRectGetHeight(bgView.frame)-CGRectGetMinY(titleLabel.frame)-2.5)];
        alertLabel.text=[NSString stringWithFormat:@"%@", userInfo[@"aps"][@"alert"]];
        alertLabel.font=[UIFont systemFontOfSize:12];
        alertLabel.numberOfLines=2;
        alertLabel.backgroundColor=[UIColor clearColor];
        alertLabel.textColor=[UIColor whiteColor];
        [bgView addSubview:alertLabel];


        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [alertLabel removeFromSuperview];
            [bgView removeFromSuperview];
            [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];


        });


        //        UIAlertController *alertController=[UIAlertController alertControllerWithTitle:@"新消息" message:userInfo[@"aps"][@"alert"] preferredStyle:UIAlertControllerStyleAlert];
        //        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        //        }];
        //        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"查看" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //            [self goToMssageViewControllerWith:userInfo];
        //
        //        }];
        //        [alertController addAction:cancelAction];
        //        [alertController addAction:okAction];
        //        [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
        //
    }
    else {
        //這里是app未運行或者在后臺,通過點擊手機通知欄的推送消息打開app時可以在這里進行處理,比如,拿到推送里的內容或者附加      字段(假設,推送里附加了一個url為 www.baidu.com),那么你就可以拿到這個url,然后進行跳轉到相應店web頁,當然,不一定必須是web頁,也可以是你app里的任意一個controll,跳轉的話用navigation或者模態視圖都可以

        [self goToMssageViewControllerWith:userInfo];
        //        mytabBar.selectedIndex=2;



    }


    completionHandler(UIBackgroundFetchResultNewData);


}
- (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 propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {

    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
#pragma mark - 當運行在后臺時,根據推送消息類型跳轉界面、進行處理
- (void)goToMssageViewControllerWith:(NSDictionary*)msgDic{
    NSUserDefaults*pushJudge = [NSUserDefaults standardUserDefaults];
    [pushJudge setObject:msgDic forKey:@"push"];
    [pushJudge synchronize];
//    [UIApplication sharedApplication].applicationIconBadgeNumber=0;
    [pushJudge setObject:@"" forKey:@"MesNum"];


    NSString *type=msgDic[@"msgtype"];




    //    if ([type isEqual:@"order"]) {//我的訂單界面
    //
    //        QCMyOrderVC *orderVC=[[QCMyOrderVC alloc]initWithNibName:@"QCMyOrderVC" bundle:nil]; UINavigationController *mm=[[UINavigationController alloc]initWithRootViewController:orderVC];
    //        [self.window.rootViewController presentViewController:mm animated:YES completion:nil ];
    //    }else if ([type isEqual:@"car_report"])//車檢報告界面
    //    {
    //        QCCheJianBaoGaoVC *orderVC=[[QCCheJianBaoGaoVC alloc]initWithNibName:@"QCCheJianBaoGaoVC" bundle:nil]; UINavigationController *mm=[[UINavigationController alloc]initWithRootViewController:orderVC];
    //        orderVC.push_Car=[NSString stringWithFormat:@"%@%@%@",msgDic[@"carBrand"],msgDic[@"carSeries"],msgDic[@"carModel"]];
    //        orderVC.push_cardId=msgDic[@"carId"];
    //        [self.window.rootViewController presentViewController:mm animated:YES completion:nil ];
    //
    //
    //    }else if ([type isEqual:@"activity"])//活動界面
    //    {
    //
    //
    //        NSString *urlString=msgDic[@"url"];
    //        NSURL*url=[NSURL URLWithString:urlString];
    //        [[UIApplication sharedApplication] openURL:url];
    //
    //
    //
    //    }else if ([type isEqual:@"coupon"])//優惠券界面
    //    {
    //        [self _IsNotFirst];
    //        self.mytabBar.selectedIndex=1;
    //    }else if ([type isEqual:@"refund_success"])//退款成功界面
    //    {
    //        QCCustomRecordVC *orderVC=[[QCCustomRecordVC alloc]initWithNibName:@"QCCustomRecordVC" bundle:nil];
    //        UINavigationController *mm=[[UINavigationController alloc]initWithRootViewController:orderVC];
    //        [self.window.rootViewController presentViewController:mm animated:YES completion:nil ];
    //
    //
    //    }else if ([type isEqual:@"refund_failed"])//退款失敗
    //    {
    //        QCMyWalletVC *orderVC=[[QCMyWalletVC alloc]initWithNibName:@"QCMyWalletVC" bundle:nil];
    //        UINavigationController *mm=[[UINavigationController alloc]initWithRootViewController:orderVC];
    //        [self.window.rootViewController presentViewController:mm animated:YES completion:nil ];
    //
    //
    //    }
    //    else if ([type isEqual:@"version"])//版本相關
    //    {
    //        [self _IsNotFirst];
    //        self.mytabBar.selectedIndex=0;
    //
    //
    //    }
    //    else if ([type isEqual:@"comment"])//評論相關
    //    {
    //        QCMyOrderVC *orderVC=[[QCMyOrderVC alloc]initWithNibName:@"QCMyOrderVC" bundle:nil]; UINavigationController *mm=[[UINavigationController alloc]initWithRootViewController:orderVC];
    //        [self.window.rootViewController presentViewController:mm animated:YES completion:nil ];
    //
    //    }
}

-(void)ClickTap:(UITapGestureRecognizer*)tap
{
    [self goToMssageViewControllerWith:msg];
    
    UIView *bgview=tap.view;
    [bgview removeFromSuperview];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
    
}
+ (void)showLocalNotificationAtFront:(UILocalNotification *)notification {
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
    return;
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容