宝宝最近带着血光学了点关于推送的东西,
1.获取deviceToken后要转换成16进制上传给服务器
以下是转换方法
//把deviceToken变成16进制字符串
- (NSString *)getHEX:(NSData *)data
{
if (!data || [data length] == 0) {
return @"";
}
NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
[data enumerateByteRangesUsingBlock:^(const void * bytes, NSRange byteRange, BOOL *stop) {
unsigned char *dataBytes = (unsigned char*)bytes;
for (NSInteger i = 0; i < byteRange.length; i++) {
NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
if ([hexStr length] == 2) {
[string appendString:hexStr];
} else {
[string appendFormat:@"0%@", hexStr];
}
}
}];
return string;
}
2.接收到通知后 判断是前台运行还是后台运行
//接收远程推送的消息
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void(^)(UIBackgroundFetchResult))completionHandler {
//接到
//取出消息体
NSString *messageAlert = [[userInfo objectForKey:@"aps"]objectForKey:@"alert"];
NSString * type = [userInfo objectForKey:@"type"];
if (application.applicationState == UIApplicationStateActive) {
//程序处于前台
NSLog(@"active");
//把icon上的小图标设置为0
[application setApplicationIconBadgeNumber:0];
//获取当前的控制器 因为我的控制器是以navigation存在 所以比较好取出
UINavigationController * nav = (UINavigationController *)self.window.rootViewController;
UIViewController * currentVC = [nav.viewControllers lastObject];
//弹框通知
UIAlertController * stateAlert = [UIAlertController alertControllerWithTitle:@"远程通知" message:messageAlert preferredStyle:UIAlertControllerStyleAlert];
[stateAlert addAction:[UIAlertAction actionWithTitle:@"前往" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"前往点击");
//去指定的VC控制器
[self goToDesignatedVC:type withUserInfo:userInfo];
}]];
[stateAlert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
[currentVC presentViewController:stateAlert animated:YES completion:nil];
}
else if(application.applicationState == UIApplicationStateInactive){
//程序处于后台
//去指定的VC控制器
[self goToDesignatedVC:type withUserInfo:userInfo];
}
NSLog(@"userInfo %@",userInfo);
}
3.根据推送消息的类型不同 实现不同的处理方法 (只写了一个)
-(void)goToDesignatedVC:(NSString *)type withUserInfo:(NSDictionary *)userInfo{
NSInteger typeInt = type.intValue;
switch (typeInt) {
case 1:
{
//收到订单的通知处理方法
NSLog(@"appdelegate进入远程通知,收取订单选项");
NSString * order_id = userInfo[@"order_id"];
//通知订单列表页面 跳转进入订单详情页面
[[NSNotificationCenter defaultCenter] postNotificationName:@"tabBarTalkToOrderVCNoti" object:order_id];
}
break;
case 2:
{
}
break;
default:
break;
}
}
4.注意 我是用通知去跳转指定页面
一定要一层一层去扒开这些VC的衣服去跳转!
比如我就扒了两层 先发通知扒了TabBarViewControlle 再从这一页面继续发通知进入我需要的页面!