evollu / react-native-fcm

react native module for firebase cloud messaging and local notification
MIT License
1.73k stars 681 forks source link

iOS can't read local notification body #644

Open KlimczakM opened 7 years ago

KlimczakM commented 7 years ago

Version: 10.0.3 Tested on: iOS 9.3 and iOS 11.1 Language: TypeScript

Scheduled local notifications seem to work fine when the app is in the background. But when I receive them in the foreground I can't access their body - the notif.notification is undefined.

Receive notifications:

FCM.on(FCMEvent.Notification, async (notif) => {
    if (notif.local_notification) {
        console.log("notif.notification: " + notif.notification)
    }
})

Schedule local notification:

FCM.scheduleLocalNotification({
    fire_date: fireDate,
    id: notificationId,
    body: message,
    show_in_foreground: true,
})

I'd like to show an alert when I receive a local notification (with a notification body) in the foreground, how can I do that?

evollu commented 7 years ago

for local notification, notif itself contains everything.

KlimczakM commented 7 years ago

As far as I can see, notif is Notification type, which is:

export interface Notification {
    collapse_key: string;
    opened_from_tray: boolean;
    from: string;
    notification: {
        title?: string
        body: string;
        icon: string;
    };
    local_notification?: boolean;
    _notificationType: string;
    finish(type?: string): void;
}

So how can I access the notification body differently than using notif.notification?

evollu commented 7 years ago

sorry that type definition is not 100 percent correct. notification object varies a bit depends on the way notification gets created and delivered. console.log the notification you get will get a better idea what field to use

KlimczakM commented 7 years ago

Ok, now I understand. So this is the solution:

FCM.on(FCMEvent.Notification, async (notif) => {
    if (notif.local_notification) {
        const localNotification = <any>notif as LocalNotification
        // ...
    }
})

Unfortunately, you have to force casting.

Edit: and this is the LocalNotificaiton object (I posted base Notification object above):

  export interface LocalNotification {
    id?: string;
    title?: string;
    body: string;
    icon?: string;
    vibrate?: number;
    sound?: string;
    big_text?: string;
    sub_text?: string;
    color?: string;
    large_icon?: string;
    priority?: string;
    show_in_foreground?: boolean;
    click_action?: string;
    badge?: number;
    number?: number;
    ticker?: string;
    auto_cancel?: boolean;
    group?: string;
    picture?: string;
    my_custom_data?: string;
    ongoing?: boolean;
    lights?: boolean;
}
evollu commented 6 years ago

hmm...yes