8***@qq.com
8***@qq.com
  • 发布:2023-04-13 09:28
  • 更新:2023-04-17 10:59
  • 阅读:178

【报Bug】HBuilder ios sdk集成个推后,能获取到clientId,但是无法获取deviceToken

分类:uni-app

产品分类: uniapp/App

PC开发环境操作系统: Mac

PC开发环境操作系统版本号: mac12

HBuilderX类型: 正式

HBuilderX版本号: 3.7.6

手机系统: iOS

手机系统版本号: iOS 14

手机厂商: 苹果

手机机型: iphone 8p

页面类型: vue

vue版本: vue2

打包方式: 离线

项目创建方式: HBuilderX

示例代码:
//  
//  AppDelegate.m  
//  Pandora  
//  
//  Created by Mac Pro_C on 12-12-26.  
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.  
//  

#import "AppDelegate.h"  
#import "PDRCore.h"  
#import <AVFoundation/AVFoundation.h>  
#import "PDRCommonString.h"  
#import "ViewController.h"  
#import "PDRCoreApp.h"  
#import "PDRCoreAppManager.h"  
#import "GTSDK/GeTuiSdk.h"  
#import <UserNotifications/UserNotifications.h>  

// 个推开发者网站中申请App时,注册的AppId、AppKey、AppSecret  
#define kGtAppId           @"xxx"  
#define kGtAppKey          @"xxx"  
#define kGtAppSecret       @"xxx"  

@interface AppDelegate()<PDRCoreDelegate, GeTuiSdkDelegate, UNUserNotificationCenterDelegate>  
@property (strong, nonatomic) ViewController *h5ViewContoller;  
@end  

@implementation AppDelegate  

@synthesize window = _window;  
@synthesize rootViewController;  
#pragma mark -  
#pragma mark app lifecycle  

/*  
 * @Summary:程序启动时收到push消息  
 */  
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
{  
    BOOL ret = [PDRCore initEngineWihtOptions:launchOptions  
                                  withRunMode:PDRCoreRunModeNormal withDelegate:self];  

    UIWindow *window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];  
    self.window = window;  

    ViewController *viewController = [[ViewController alloc] init];  
    self.h5ViewContoller = viewController;  

    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];  
    self.rootViewController = navigationController;  
    navigationController.navigationBarHidden = YES;  
    {  
        [self startMainApp];  
        self.h5ViewContoller.showLoadingView = YES;  
    }  
    self.window.rootViewController = navigationController;  
    [self.window makeKeyAndVisible];  

    NSLog(@" ----- 1111 ----");  
    // start getui  
    // [ GTSDK ]:使用APPID/APPKEY/APPSECRENT启动个推  
    [GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self launchingOptions:launchOptions];  

    NSLog(@" ----- 2222 ----");  
    // 注册远程通知  
    [GeTuiSdk registerRemoteNotification: (UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge)];  

    NSLog(@" ----- 3333 ----");  

    NSLog(@"ret11111 ====== %@", ret?@"YES":@"NO");  
    NSLog(@" ----- 3333 ----");  
    return ret;  
}  

// getui  
+ (void)startSdkWithAppId:(NSString *)appid appKey:(NSString *)appKey appSecret:(NSString *)appSecret delegate:(id<GeTuiSdkDelegate>)delegate launchingOptions:(NSDictionary * __nullable)launchOptions{  

}  

/** SDK启动成功返回cid */  
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {  
    // 个推SDK已注册,返回clientId  
    NSLog(@" ----- clientId: %@", clientId);  
}  

/// [ GTSDK回调 ] SDK运行状态通知  
- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus {  
    NSLog(@" -----AAAA@");  
    // [[NSNotificationCenter defaultCenter] postNotificationName:GTSdkStateNotification object:self];  
}  

- (void)GeTuiSdkDidOccurError:(NSError *)error {  
    NSLog(@" -----BBBB: @");  
    NSString *msg = [NSString stringWithFormat:@"[ TestDemo ] [GeTuiSdk GeTuiSdkDidOccurError]:%@\n\n",error.localizedDescription];  
    // [self.homePage logMsg:msg];  
}  

//MARK: - 通知回调  

/// 通知授权结果(iOS10及以上版本)  
/// @param granted 用户是否允许通知  
/// @param error 错误信息  
- (void)GetuiSdkGrantAuthorization:(BOOL)granted error:(NSError *)error {  
    NSString *msg = [NSString stringWithFormat:@"[ TestDemo ] [APNs] %@ \n%@ %@", NSStringFromSelector(_cmd), @(granted), error];  
    // [self.homePage logMsg:msg];  
}  

/// 通知展示(iOS10及以上版本)  
/// @param center center  
/// @param notification notification  
/// @param completionHandler completionHandler  
- (void)GeTuiSdkNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification completionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {  
    NSString *msg = [NSString stringWithFormat:@"[ TestDemo ] [APNs] %@ \n%@", NSStringFromSelector(_cmd), notification.request.content.userInfo];  
    // [self.homePage logMsg:msg];  
    NSLog(@" -----7777: %@", msg);  

    // [ 参考代码,开发者注意根据实际需求自行修改 ] 根据APP需要,判断是否要提示用户Badge、Sound、Alert等  
    //completionHandler(UNNotificationPresentationOptionNone); 若不显示通知,则无法点击通知  
    completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);  
}  

/// 收到通知信息  
/// @param userInfo apns通知内容  
/// @param center UNUserNotificationCenter(iOS10及以上版本)  
/// @param response UNNotificationResponse(iOS10及以上版本)  
/// @param completionHandler 用来在后台状态下进行操作(iOS10以下版本)  
- (void)GeTuiSdkDidReceiveNotification:(NSDictionary *)userInfo notificationCenter:(UNUserNotificationCenter *)center response:(UNNotificationResponse *)response fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {  
    NSString *msg = [NSString stringWithFormat:@"[ TestDemo ] [APNs] %@ \n%@", NSStringFromSelector(_cmd), userInfo];  
    // [self.homePage logMsg:msg];  
    NSLog(@" -----8888: %@", msg);  

    if(completionHandler) {  
        // [ 参考代码,开发者注意根据实际需求自行修改 ] 根据APP需要自行修改参数值  
        completionHandler(UIBackgroundFetchResultNoData);  
    }  
}  

/// 收到透传消息  
/// @param userInfo    推送消息内容  
/// @param fromGetui   YES: 个推通道  NO:苹果apns通道  
/// @param offLine     是否是离线消息,YES.是离线消息  
/// @param appId       应用的appId  
/// @param taskId      推送消息的任务id  
/// @param msgId       推送消息的messageid  
/// @param completionHandler 用来在后台状态下进行操作(通过苹果apns通道的消息 才有此参数值)  
- (void)GeTuiSdkDidReceiveSlience:(NSDictionary *)userInfo fromGetui:(BOOL)fromGetui offLine:(BOOL)offLine appId:(NSString *)appId taskId:(NSString *)taskId msgId:(NSString *)msgId fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {  
    // [ GTSDK ]:汇报个推自定义事件(反馈透传消息),开发者可以根据项目需要决定是否使用, 非必须  
    // [GeTuiSdk sendFeedbackMessage:90001 andTaskId:taskId andMsgId:msgId];  
    NSString *msg = [NSString stringWithFormat:@"[ TestDemo ] [APN] %@ \nReceive Slience: fromGetui:%@ appId:%@ offLine:%@ taskId:%@ msgId:%@ userInfo:%@ ", NSStringFromSelector(_cmd), fromGetui ? @"个推消息" : @"APNs消息", appId, offLine ? @"离线" : @"在线", taskId, msgId, userInfo];  
    // [self.homePage logMsg:msg];  
    NSLog(@" -----9999: %@", msg);  

    //本地通知UserInfo参数  
    NSDictionary *dic = nil;  
    if (fromGetui) {  
        //个推在线透传  
        dic = @{@"_gmid_": [NSString stringWithFormat:@"%@:%@", taskId ?: @"", msgId ?: @""]};  
    } else {  
        //APNs静默通知  
        dic = userInfo;  
    }  
    if (fromGetui && offLine == NO) {  
        //个推通道+在线,发起本地通知  
        // [Utils pushLocalNotification:userInfo[@"payload"] userInfo:dic];  
    }  
    if(completionHandler) {  
        // [ 参考代码,开发者注意根据实际需求自行修改 ] 根据APP需要自行修改参数值  
        completionHandler(UIBackgroundFetchResultNoData);  
    }  
}  

- (void)GeTuiSdkNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification {  
    // [ 参考代码,开发者注意根据实际需求自行修改 ] 根据APP需要自行修改参数值  
}  

// 语音播报  
- (void)playAudioTitle:(NSString*) aText {  
    // 后台语音播报需要设置  
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];  

    AVSpeechSynthesizer * av = [[AVSpeechSynthesizer alloc] init];  
    AVSpeechUtterance * utterance = [[AVSpeechUtterance alloc]initWithString:aText];  
    AVSpeechSynthesisVoice * voiceType = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];  
    utterance.voice = voiceType;  
    utterance.rate = 0.5;  
    [av speakUtterance:utterance];  
}  

-(BOOL)getStatusBarHidden {  
    return [self.h5ViewContoller getStatusBarHidden];  
}  

-(UIStatusBarStyle)getStatusBarStyle {  
    return [self.h5ViewContoller getStatusBarStyle];  
}  
-(void)setStatusBarStyle:(UIStatusBarStyle)statusBarStyle {  
    [self.h5ViewContoller setStatusBarStyle:statusBarStyle];  
}  

-(void)wantsFullScreen:(BOOL)fullScreen  
{  
    [self.h5ViewContoller wantsFullScreen:fullScreen];  
}  

#pragma mark -  
- (void)startMainApp {  
    dispatch_async(dispatch_get_main_queue(), ^(void) {  
        [[PDRCore Instance] start];  
    });  
}  

- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem  
  completionHandler:(void(^)(BOOL succeeded))completionHandler{  
    [PDRCore handleSysEvent:PDRCoreSysEventPeekQuickAction withObject:shortcutItem];  
    completionHandler(true);  
}  

- (void)applicationDidBecomeActive:(UIApplication *)application  
{  
    [PDRCore handleSysEvent:PDRCoreSysEventBecomeActive withObject:nil];  

    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.  
}  

- (void)applicationWillResignActive:(UIApplication *)application  
{  
    [PDRCore handleSysEvent:PDRCoreSysEventResignActive withObject:nil];  

    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.  
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.  
}  

- (void)applicationDidEnterBackground:(UIApplication *)application  
{  
    [PDRCore handleSysEvent:PDRCoreSysEventEnterBackground withObject:nil];  
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.  
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.  
}  

- (void)applicationWillEnterForeground:(UIApplication *)application  
{  
    [PDRCore handleSysEvent:PDRCoreSysEventEnterForeGround withObject:nil];  
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.  
}  

- (void)applicationWillTerminate:(UIApplication *)application  
{  
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.  
    [PDRCore destoryEngine];  
}  

#pragma mark -  
#pragma mark URL  

- (BOOL)application:(UIApplication *)application  
            openURL:(NSURL *)url  
  sourceApplication:(NSString *)sourceApplication  
         annotation:(id)annotation {  
    [self application:application handleOpenURL:url];  
    return YES;  
}  

/*  
 * @Summary:程序被第三方调用,传入参数启动  
 *  
 */  
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url  
{  
    [PDRCore handleSysEvent:PDRCoreSysEventOpenURL withObject:url];  
    return YES;  
}  
- (BOOL)application:(UIApplication *)application openURL:(nonnull NSURL *)url options:(nonnull NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {  
    [PDRCore handleSysEvent:PDRCoreSysEventOpenURLWithOptions withObject:@[url,options]];  
    return YES;  
}  
/*  
 * @Summary:远程push注册成功收到DeviceToken回调  
 *  
 */  
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken  
{  
    NSLog(@" ----- 5555 -----------@");  
    NSLog(@"application-------didRegisterForRemoteNotificationsWithDeviceToken[%@]", deviceToken);  
    [PDRCore handleSysEvent:PDRCoreSysEventRevDeviceToken withObject:deviceToken];  

    // getui  
    // NSString *token = [Utils getHexStringForData:deviceToken];  
    // [self.homePage updateDeviceToken:token];  
    // NSString *errorMsg = [NSString stringWithFormat:@"[ TestDemo ] [ DeviceToken(NSString) ]: %@\n\n", token];  
    // [self.homePage logMsg:errorMsg];  
}  

/*  
 * @Summary: 远程push注册失败  
 */  
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error  
{  
    NSLog(@" ----- 6666 -----------@");  
    [PDRCore handleSysEvent:PDRCoreSysEventRegRemoteNotificationsError withObject:error];  

    // getui  
    //NSString *msg = [NSString stringWithFormat:@"[ TestDemo ] %@: %@", NSStringFromSelector(_cmd), error.localizedDescription];  
    //[self.homePage logMsg:msg];  
}  

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {  
    [PDRCore handleSysEvent:PDRCoreSysEventRevRemoteNotification withObject:userInfo];  
}  

- (void)application:(UIApplication *)application  
didReceiveRemoteNotification:(NSDictionary *)userInfo  
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {  
    [self application:application didReceiveRemoteNotification:userInfo];  
    completionHandler(UIBackgroundFetchResultNewData);  
}  

/*  
 * @Summary:程序收到本地消息  
 */  
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification  
{  
    [PDRCore handleSysEvent:PDRCoreSysEventRevLocalNotification withObject:notification];  
}  

@end  

@implementation UINavigationController(Orient)  

-(BOOL)shouldAutorotate{  
    return ![PDRCore Instance].lockScreen;  
    return YES;  
}  

- (UIInterfaceOrientationMask)supportedInterfaceOrientations{  
    if([self.topViewController isKindOfClass:[ViewController class]])  
        return [self.topViewController supportedInterfaceOrientations];  
    return UIInterfaceOrientationMaskPortrait;  
}  
@end  

操作步骤:

启动项目后真机调试打印出了clientid,没有打印deviceToken

预期结果:

打印出deviceToken

实际结果:

启动项目后真机调试打印出了clientid,没有打印deviceToken

bug描述:

使用个推的sdk能获取到deviceToken,一旦将个推的代码集成到hbuilder ios sdk后无法获取到deviceToken,代码既不走获取token成功的方法,也不走获取token失败的方法,个推那边的工作人员反馈说可能是被hbuilder 给拦截了,麻烦尽快帮忙处理下,我需要怎么做才能不被拦截。我已经将主target和notice target的通知权限都打开了。也开启了 remote notice

2023-04-13 09:28 负责人:DCloud_iOS_WZT 分享
已邀请:
DCloud_iOS_WZT

DCloud_iOS_WZT

UniPush内置个推 离线参考https://nativesupport.dcloud.net.cn/AppDocs/usemodule/iOSModuleConfig/push.html 集成即可

DCloud_iOS_WZT

DCloud_iOS_WZT

如果要自己开发插件需要添加 liblibPush.a 根据hook class 这种方式取deviceToken
https://nativesupport.dcloud.net.cn/NativePlugin/course/ios.html#hook%E7%B3%BB%E7%BB%9F%E4%BA%8B%E4%BB%B6

  • 8***@qq.com (作者)

    好的,感谢。

    2023-04-13 16:45

  • 8***@qq.com (作者)

    麻烦看下我最新的回复。

    2023-04-17 10:59

8***@qq.com

8***@qq.com (作者)

我按照https://nativesupport.dcloud.net.cn/AppDocs/usemodule/iOSModuleConfig/push.html 在feature.plist添加了内容后,报错:'setAutoNotification:' not defined in Plugin 'Push',已经检查3遍了,和官网截图一模一样。配置如下图所示。

同时我注意但第三方依赖的版本,官方用的是2.7.2 而我在个推官网下载的是最新的版本 3.0和这个有关系吗

  • DCloud_iOS_WZT

    这个配置是 用内置push模块的时候配的 你自己开发插件不用配这个

    2023-04-17 16:03

  • 8***@qq.com (作者)

    回复 DCloud_iOS_WZT: 我去掉了feature.plist的配置后还是报错:'setAutoNotification:' not defined in Plugin 'Push',已经引入了liblibPush.a、libUniPush.a、GTSDK.xcframework,libc++.tbd、libsqlite3.tbd、libz.tbd、libresolv.tbd、UserNotifications.framework、Security.framework、MobileCoreServices.framework、SystemConfiguration.framework、CoreLocation.framework、AVFoundation.framework、CoreTelephony.framework、

    2023-04-17 17:04

  • 8***@qq.com (作者)

    可能没有添加feature.plist之前就有这个错误,可能是我之前没有看到这个错误。

    2023-04-17 17:06

  • DCloud_iOS_WZT

    回复 8***@qq.com: 你应用里用到了plus.push.setAutoNotification 这个api吗

    2023-04-17 17:09

  • 8***@qq.com (作者)

    回复 DCloud_iOS_WZT: 我代码里面没有地方写 这行代码,是不是个推的sdk里面有这行代码 plus.push.setAutoNotification

    2023-04-17 17:10

  • 8***@qq.com (作者)

    回复 DCloud_iOS_WZT: 这行代码是不是包含在了:liblibPush.a、libUniPush.a 里面,导致报这个错误。

    2023-04-17 17:20

要回复问题请先登录注册