• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

ios - Firebase 消息传递方法 swizzling 不起作用

[复制链接]
菜鸟教程小白 发表于 2022-12-11 18:12:09 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

您好,我正在实现 FCM(Fire base 云消息传递)。我已经让应用程序从 FCM 控制台接收通知和数据。我有我的服务器通知和 Firebase 通知。我想分别处理两种类型的通知(来 self 的服务器和来自 FCM)。我已经浏览了文档,这可以通过在 AppDelegate 中调整通知处理程序来实现

但问题是我只能在

中获取FCM消息数据(IOS 10)
-(void)userNotificationCenterUNUserNotificationCenter *)center willPresentNotificationUNNotification *)notification withCompletionHandlervoid (^)(UNNotificationPresentationOptions))completionHandler {}

-(void)userNotificationCenterUNUserNotificationCenter *)center didReceiveNotificationResponseUNNotificationResponse *)response withCompletionHandlervoid (^)())completionHandler {}

FCM 委托(delegate)的回调

// The callback to handle data message received via FCM for devices running iOS 10 or above.
- (void)applicationReceivedRemoteMessagenonnull FIRMessagingRemoteMessage *)remoteMessage {

    // Print full message
    NSLog(@"Can get here firebase?%@", [remoteMessage appData]);
}

上面的回调永远不会被调用

我们如何使用 swizzling 单独设置 FCM 处理程序消息?

这是我的 Appdelegate didfinishlaunchingwith 选项

    application.applicationIconBadgeNumber = 0;

    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
        UIUserNotificationType allNotificationTypes =
        (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings =
        [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    } else {
        // iOS 10 or later
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
        UNAuthorizationOptions authOptions =
        UNAuthorizationOptionAlert
        | UNAuthorizationOptionSound
        | UNAuthorizationOptionBadge;
        [[UNUserNotificationCenter currentNotificationCenter]
         requestAuthorizationWithOptions:authOptions
         completionHandler:^(BOOL granted, NSError * _Nullable error) {
         }
         ];

        // For iOS 10 display notification (sent via APNS)
        [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
        // For iOS 10 data message (sent via FCM)

        [[FIRMessaging messaging] setRemoteMessageDelegate:self];
#endif
    }

    [[UIApplication sharedApplication] registerForRemoteNotifications];

    // [START configure_firebase]
    [FIRApp configure];
    // [END configure_firebase]
    // Add observer for InstanceID token refresh callback.
    [[NSNotificationCenter defaultCenter] addObserver:self selectorselector(tokenRefreshNotification
                                                 name:kFIRInstanceIDTokenRefreshNotification object:nil];    

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];

    _rootViewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];


    [self.window setRootViewController:_rootViewController];
    [self.window makeKeyAndVisible];

    NSDictionary *remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (remoteNotification)
        [self handleRemoteNotification:remoteNotification shouldPrompt:NO];

    self.isFirstTime = true;
    self.isJustForRefresh = 0;

    return YES;

有人知道如何让它工作吗?

编辑:这是我的观察者观察函数和didregisterRemoteNotification函数

// [START refresh_token]
- (void)tokenRefreshNotificationNSNotification *)notification {
    // Note that this callback will be fired everytime a new token is generated, including the first
    // time. So if you need to retrieve the token as soon as it is available this is where that
    // should be done.
    NSString *refreshedToken = [[FIRInstanceID instanceID] token];
    NSLog(@"InstanceID token: %@", refreshedToken);

    // Connect to FCM since connection may have failed when attempted before having a token.
    [self connectToFcm];

    // TODO: If necessary send token to application server.
}
// [END refresh_token]

// [START connect_to_fcm]
- (void)connectToFcm {
    [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
        if (error != nil) {
            NSLog(@"Unable to connect to FCM. %@", error);
        } else {
            NSLog(@"Connected to FCM.");
        }
    }];
}
// [END connect_to_fcm]

- (void)applicationUIApplication*)application didRegisterForRemoteNotificationsWithDeviceTokenNSData*)deviceToken {
    NSString *sanitizedDeviceToken = [[[[deviceToken description]
                                        stringByReplacingOccurrencesOfString"<" withString""]
                                       stringByReplacingOccurrencesOfString">" withString""]
                                      stringByReplacingOccurrencesOfString" " withString""];

    DLog(@"sanitized device token: %@", sanitizedDeviceToken);
    [PushNotificationManager API_registerAPNSToken:sanitizedDeviceToken
                                      onCompletion:^(BOOL success, NSError *error){}];

    [[FIRInstanceID instanceID]setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];

}

更新:我已包含此功能但仍无法正常工作

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    if (userInfo[@"gcm.message_id"] != nil) {
        NSLog(@"Should get here FCM?");
        [[FIRMessaging messaging]appDidReceiveMessage:userInfo];
    }else {
        NSLog(@"test fetchCompletion handler: %@",userInfo.description);
    }

}



Best Answer-推荐答案


你可以看看这个答案吗?好像你错过了 FIRMessaging.messaging().connect(){....

https://stackoverflow.com/a/40881754/1005570

还有委托(delegate)函数..

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
             fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification

// Print message ID.
print("Message ID: \(userInfo["gcm.message_id"]!)")

// Print full message.
print(userInfo)

FIRMessaging.messaging().appDidReceiveMessage(userInfo)

}

关于ios - Firebase 消息传递方法 swizzling 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40901942/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap