Skip to content

Cloud Messaging reference

At a glance

  • Messaging.messaging(): add_token_listener(listener), add_registration_listener, add_unregistration_listener (each returns a remove function); token(cb), fcm_token, delete_token(cb), retrieve_fcm_token(sender_id, cb), delete_fcm_token(sender_id, cb), auto_init_enabled, installation_id_enabled, register(cb), unregister(cb), delete_data(cb), subscribe_to_topic(topic, cb), unsubscribe_from_topic(topic, cb), apns_token, set_apns_token(token, type), app_did_receive_message(user_info)
  • MessagingError (name), MessagingErrorCode, APNSTokenType, MessagingMessageStatus, MESSAGING_ERROR_DOMAIN
  • notifications: request_permission(options, cb), authorization_status(cb), register_for_remote_notifications(), set_handlers(on_foreground, on_open, *, default_presentation); Notification (identifier, title, subtitle, body, badge, data, category, thread_id, date, message_id); AuthorizationOptions, AuthorizationStatus, PresentationOptions, DEFAULT_ACTION, DISMISS_ACTION

pyios_firebase.messaging

Firebase Cloud Messaging: push notifications and messages to this device.

from pyios_firebase.messaging import Messaging

messaging = Messaging.messaging()
messaging.add_token_listener(lambda token: send_to_my_server(token))
messaging.subscribe_to_topic("news", lambda error: ...)

To ask for permission and handle the notifications that arrive, see pyios_firebase.messaging.notifications.

The app needs the Push Notifications capability, and an APNs key uploaded in the Firebase console. Messages do not reach the iOS Simulator from FCM (only xcrun simctl push test payloads do).

Needs the FirebaseMessaging framework.

Modules:

Name Description
messaging

Messaging: the FCM registration token, topics and registration.

notifications

Notification permission, and notifications that arrive (UserNotifications).

Classes:

Name Description
APNSTokenType

The APNs environment of a token (FIRMessagingAPNSTokenType).

Messaging

Firebase Cloud Messaging. Get it with Messaging.messaging().

MessagingError

An error from Firebase Cloud Messaging.

MessagingErrorCode

The error.code values of Messaging errors (FIRMessagingError).

MessagingMessageStatus

What app_did_receive_message found (FIRMessagingMessageStatus).

Attributes:

Name Type Description
MESSAGING_ERROR_DOMAIN Final

The error.domain of Messaging errors.

MESSAGING_ERROR_DOMAIN module-attribute

MESSAGING_ERROR_DOMAIN: Final = 'com.google.fcm'

The error.domain of Messaging errors.

APNSTokenType

The APNs environment of a token (FIRMessagingAPNSTokenType).

Attributes:

Name Type Description
UNKNOWN Final

Found from the provisioning profile (the usual choice).

SANDBOX Final

Development builds.

PROD Final

App Store, TestFlight and ad hoc builds.

UNKNOWN class-attribute instance-attribute

UNKNOWN: Final = 0

Found from the provisioning profile (the usual choice).

SANDBOX class-attribute instance-attribute

SANDBOX: Final = 1

Development builds.

PROD class-attribute instance-attribute

PROD: Final = 2

App Store, TestFlight and ad hoc builds.

Messaging

Messaging(native: ObjCObject)

Firebase Cloud Messaging. Get it with Messaging.messaging().

Notifications need the push entitlement and an APNs key in the Firebase console; see pyios_firebase.messaging.notifications to ask permission and handle what arrives.

Parameters:

Name Type Description Default
native ObjCObject

the native FIRMessaging.

required

Methods:

Name Description
messaging

The shared Messaging.

add_token_listener

Call listener(token) with each new FCM registration token: at

add_registration_listener

Call listener(installation_id) when the app registers with FCM

add_unregistration_listener

Call listener(installation_id) after unregister worked.

set_apns_token

Set the APNs device token, with its environment.

token

Get the FCM registration token (made if needed; needs the APNs token

delete_token

Delete the FCM registration token: the device stops getting messages

retrieve_fcm_token

Get a token for another sender (another Firebase project's sender ID).

delete_fcm_token

Delete the token of another sender.

register

Register with FCM through the Firebase installation ID (with

unregister

Stop getting messages through the installation ID.

delete_data

Delete this app instance's FCM registrations, here and on the server.

subscribe_to_topic

Get the messages sent to a topic.

unsubscribe_from_topic

Stop getting a topic's messages.

app_did_receive_message

Tell FCM a message arrived (for delivery analytics). Only needed when

Attributes:

Name Type Description
native ObjCObject

The FIRMessaging.

apns_token bytes | None

The APNs device token. Firebase sets it for you (app delegate

fcm_token str | None

The FCM registration token, if there is one yet (else use token).

auto_init_enabled bool

Make a token automatically at start-up (on by default). Setting it is

installation_id_enabled bool

Whether the app registers through its Firebase installation ID

native property

native: ObjCObject

The FIRMessaging.

apns_token property writable

apns_token: bytes | None

The APNs device token. Firebase sets it for you (app delegate swizzling); set it yourself when FirebaseAppDelegateProxyEnabled is NO.

fcm_token property

fcm_token: str | None

The FCM registration token, if there is one yet (else use token).

auto_init_enabled property writable

auto_init_enabled: bool

Make a token automatically at start-up (on by default). Setting it is kept across launches; to start with it off, set FirebaseMessagingAutoInitEnabled to NO in Info.plist.

installation_id_enabled property

installation_id_enabled: bool

Whether the app registers through its Firebase installation ID instead of a token (FirebaseMessagingInstallationIdEnabled in Info.plist). Then the token methods fail: use register.

messaging classmethod

messaging() -> Messaging

The shared Messaging.

add_token_listener

add_token_listener(
    listener: Callable[[str | None], None],
) -> Callable[[], None]

Call listener(token) with each new FCM registration token: at start-up (when auto-init is on) and whenever it changes. Send it to your server to target this device.

Parameters:

Name Type Description Default
listener Callable[[str | None], None]

gets the token (str).

required

Returns:

Type Description
Callable[[], None]

A function that removes the listener.

add_registration_listener

add_registration_listener(
    listener: Callable[[str | None], None],
) -> Callable[[], None]

Call listener(installation_id) when the app registers with FCM through its Firebase installation ID (with FirebaseMessagingInstallationIdEnabled in Info.plist).

Parameters:

Name Type Description Default
listener Callable[[str | None], None]

gets the installation ID.

required

Returns:

Type Description
Callable[[], None]

A function that removes the listener.

add_unregistration_listener

add_unregistration_listener(
    listener: Callable[[str | None], None],
) -> Callable[[], None]

Call listener(installation_id) after unregister worked.

Parameters:

Name Type Description Default
listener Callable[[str | None], None]

gets the installation ID that was unregistered.

required

Returns:

Type Description
Callable[[], None]

A function that removes the listener.

set_apns_token

set_apns_token(
    token: bytes, token_type: int = UNKNOWN
) -> None

Set the APNs device token, with its environment.

Parameters:

Name Type Description Default
token bytes

the token from application:didRegisterForRemoteNotificationsWithDeviceToken:.

required
token_type int

an APNSTokenType.

UNKNOWN

token

token(callback: TokenCallback) -> None

Get the FCM registration token (made if needed; needs the APNs token on a device, and the network).

Parameters:

Name Type Description Default
callback TokenCallback

gets (token, None), or (None, error).

required

delete_token

delete_token(callback: ErrorCallback | None = None) -> None

Delete the FCM registration token: the device stops getting messages until a new token is made.

Parameters:

Name Type Description Default
callback ErrorCallback | None

gets None or the error.

None

retrieve_fcm_token

retrieve_fcm_token(
    sender_id: str, callback: TokenCallback
) -> None

Get a token for another sender (another Firebase project's sender ID).

Parameters:

Name Type Description Default
sender_id str

the other project's sender ID.

required
callback TokenCallback

gets (token, None), or (None, error).

required

delete_fcm_token

delete_fcm_token(
    sender_id: str, callback: ErrorCallback | None = None
) -> None

Delete the token of another sender.

Parameters:

Name Type Description Default
sender_id str

the other project's sender ID.

required
callback ErrorCallback | None

gets None or the error.

None

register

register(callback: ErrorCallback | None = None) -> None

Register with FCM through the Firebase installation ID (with FirebaseMessagingInstallationIdEnabled). Registration listeners get the installation ID.

Parameters:

Name Type Description Default
callback ErrorCallback | None

gets None or the error.

None

unregister

unregister(callback: ErrorCallback | None = None) -> None

Stop getting messages through the installation ID.

Parameters:

Name Type Description Default
callback ErrorCallback | None

gets None or the error.

None

delete_data

delete_data(callback: ErrorCallback | None = None) -> None

Delete this app instance's FCM registrations, here and on the server. It does not delete the Firebase installation ID; turn auto-init off to stop a new registration at the next start-up.

Parameters:

Name Type Description Default
callback ErrorCallback | None

gets None or the error.

None

subscribe_to_topic

subscribe_to_topic(
    topic: str, callback: ErrorCallback | None = None
) -> None

Get the messages sent to a topic.

Parameters:

Name Type Description Default
topic str

the topic, for example "news" (1 to 900 letters, digits and - _ . ~ %).

required
callback ErrorCallback | None

gets None once subscribed, or the error.

None

Raises:

Type Description
ValueError

an invalid topic name.

unsubscribe_from_topic

unsubscribe_from_topic(
    topic: str, callback: ErrorCallback | None = None
) -> None

Stop getting a topic's messages.

Parameters:

Name Type Description Default
topic str

the topic.

required
callback ErrorCallback | None

gets None once unsubscribed, or the error.

None

Raises:

Type Description
ValueError

an invalid topic name.

app_did_receive_message

app_did_receive_message(message: Mapping[str, Any]) -> int

Tell FCM a message arrived (for delivery analytics). Only needed when FirebaseAppDelegateProxyEnabled is NO; Firebase does it for you otherwise.

Parameters:

Name Type Description Default
message Mapping[str, Any]

the notification's user_info (the APNs payload).

required

Returns:

Type Description
int

A MessagingMessageStatus.

MessagingError

Bases: FirebaseError

An error from Firebase Cloud Messaging.

Attributes:

Name Type Description
name str

The MessagingErrorCode name of code, or "" for errors from

name instance-attribute

name: str

The MessagingErrorCode name of code, or "" for errors from other domains (for example Firebase Installations).

MessagingErrorCode

The error.code values of Messaging errors (FIRMessagingError).

Attributes:

Name Type Description
AUTHENTICATION Final

The FCM backend could not validate the request (check the API key and

NETWORK Final

No network.

AUTHENTICATION class-attribute instance-attribute

AUTHENTICATION: Final = 1

The FCM backend could not validate the request (check the API key and GoogleService-Info.plist).

NETWORK class-attribute instance-attribute

NETWORK: Final = 4

No network.

MessagingMessageStatus

What app_did_receive_message found (FIRMessagingMessageStatus).

pyios_firebase.messaging.notifications

Notification permission, and notifications that arrive (UserNotifications).

Push notifications from FCM arrive through Apple's notification center. This module asks for permission, registers with APNs, and calls Python when a notification arrives with the app open, or when the user taps one::

from pyios_firebase.messaging import notifications
from pyios_firebase.messaging.notifications import AuthorizationOptions, PresentationOptions

def on_foreground(notification):
    print("got", notification.title, notification.data)
    return PresentationOptions.BANNER | PresentationOptions.SOUND  # show it

def on_open(notification, action):
    open_screen(notification.data.get("screen"))

# early, before App.run(): a tap that launched the app is delivered then
notifications.set_handlers(on_foreground=on_foreground, on_open=on_open)
notifications.request_permission(
    AuthorizationOptions.ALERT | AuthorizationOptions.BADGE | AuthorizationOptions.SOUND,
    lambda granted, error: notifications.register_for_remote_notifications(),
)

Firebase forwards the APNs token to Messaging by itself (app delegate swizzling), and records what arrives for delivery analytics.

Data-only (silent) messages are delivered to the app delegate (application:didReceiveRemoteNotification:fetchCompletionHandler:), which Python does not own in a Kivy app: send the data in a notification instead, or read it when the user opens the app.

Classes:

Name Description
AuthorizationOptions

What to ask permission for (UNAuthorizationOptions). Combine with |.

AuthorizationStatus

The permission the user gave (UNAuthorizationStatus).

PresentationOptions

How to show a notification that arrives with the app open

Notification

A notification that arrived (from UNNotification).

PyNotificationCenterDelegate

Lets iOS call the Python handlers.

Functions:

Name Description
request_permission

Ask the user for permission to show notifications. iOS asks only once;

authorization_status

The current permission.

register_for_remote_notifications

Register with APNs, to get the device token FCM needs. Call it on the

launch_hook_status

Whether the launch hook package is in the app, and working.

set_handlers

Call Python when a notification arrives with the app open, and when the

Attributes:

Name Type Description
HOOK_CLASS_NAME Final

The class of the optional launch hook package (pyios-firebase-notifications-hook),

HOOK_CLASS_NAME module-attribute

HOOK_CLASS_NAME: Final = 'PyiosFirebaseNotificationsHook'

The class of the optional launch hook package (pyios-firebase-notifications-hook), which keeps the tap that launches a Kivy app until set_handlers runs.

DEFAULT_ACTION module-attribute

DEFAULT_ACTION: Final = (
    "com.apple.UNNotificationDefaultActionIdentifier"
)

The action of on_open when the user tapped the notification itself.

DISMISS_ACTION module-attribute

DISMISS_ACTION: Final = (
    "com.apple.UNNotificationDismissActionIdentifier"
)

The action when the user dismissed it (only for categories that ask).

ForegroundHandler module-attribute

ForegroundHandler = Callable[[Notification], 'int | None']

Gets the Notification; returns PresentationOptions (or None: show nothing).

OpenHandler module-attribute

OpenHandler = Callable[[Notification, str], None]

Gets the Notification and the action (DEFAULT_ACTION for a tap).

AuthorizationOptions

What to ask permission for (UNAuthorizationOptions). Combine with |.

Attributes:

Name Type Description
CRITICAL_ALERT Final

Needs an entitlement from Apple.

PROVISIONAL Final

Granted without asking: notifications are delivered quietly, to

CRITICAL_ALERT class-attribute instance-attribute

CRITICAL_ALERT: Final = 1 << 4

Needs an entitlement from Apple.

PROVISIONAL class-attribute instance-attribute

PROVISIONAL: Final = 1 << 6

Granted without asking: notifications are delivered quietly, to Notification Center only, until the user chooses.

AuthorizationStatus

The permission the user gave (UNAuthorizationStatus).

Attributes:

Name Type Description
NOT_DETERMINED Final

Not asked yet.

EPHEMERAL Final

App Clips only.

NOT_DETERMINED class-attribute instance-attribute

NOT_DETERMINED: Final = 0

Not asked yet.

EPHEMERAL class-attribute instance-attribute

EPHEMERAL: Final = 4

App Clips only.

PresentationOptions

How to show a notification that arrives with the app open (UNNotificationPresentationOptions). Combine with |; 0 shows nothing.

Attributes:

Name Type Description
LIST Final

In Notification Center.

BANNER Final

As a banner.

LIST class-attribute instance-attribute

LIST: Final = 1 << 3

In Notification Center.

BANNER class-attribute instance-attribute

BANNER: Final = 1 << 4

As a banner.

Notification dataclass

Notification(
    identifier: str,
    title: str,
    subtitle: str,
    body: str,
    badge: int | None,
    data: dict[str, Any] = dict(),
    category: str = "",
    thread_id: str = "",
    date: datetime | None = None,
)

A notification that arrived (from UNNotification).

Methods:

Name Description
from_native

Copy a native UNNotification.

Attributes:

Name Type Description
identifier str

The request's identifier.

data dict[str, Any]

The whole payload (userInfo): the aps dictionary, and the FCM

date datetime | None

When it was delivered (UTC).

message_id str | None

The FCM message ID ("gcm.message_id"), or None if the

identifier instance-attribute

identifier: str

The request's identifier.

data class-attribute instance-attribute

data: dict[str, Any] = field(default_factory=dict)

The whole payload (userInfo): the aps dictionary, and the FCM message's data keys.

date class-attribute instance-attribute

date: datetime | None = None

When it was delivered (UTC).

message_id property

message_id: str | None

The FCM message ID ("gcm.message_id"), or None if the notification did not come from FCM.

from_native classmethod

from_native(notification: ObjCObject) -> Notification

Copy a native UNNotification.

Parameters:

Name Type Description Default
notification ObjCObject

the UNNotification.

required

PyNotificationCenterDelegate

Bases: NSObject

Lets iOS call the Python handlers.

Methods:

Name Description
userNotificationCenter_willPresentNotification_withCompletionHandler_

A notification arrived with the app open.

userNotificationCenter_didReceiveNotificationResponse_withCompletionHandler_

The user tapped a notification (or one of its actions).

userNotificationCenter_willPresentNotification_withCompletionHandler_

userNotificationCenter_willPresentNotification_withCompletionHandler_(
    center: objc_id,
    notification: objc_id,
    handler: objc_block,
) -> None

A notification arrived with the app open.

userNotificationCenter_didReceiveNotificationResponse_withCompletionHandler_

userNotificationCenter_didReceiveNotificationResponse_withCompletionHandler_(
    center: objc_id, response: objc_id, handler: objc_block
) -> None

The user tapped a notification (or one of its actions).

request_permission

request_permission(
    options: int,
    callback: Callable[[bool, FirebaseError | None], None]
    | None = None,
) -> None

Ask the user for permission to show notifications. iOS asks only once; later calls give the earlier answer without asking.

Parameters:

Name Type Description Default
options int

AuthorizationOptions, combined with |.

required
callback Callable[[bool, FirebaseError | None], None] | None

gets (granted, error). It runs on a background thread.

None

authorization_status

authorization_status(
    callback: Callable[[int], None],
) -> None

The current permission.

Parameters:

Name Type Description Default
callback Callable[[int], None]

gets an AuthorizationStatus. It runs on a background thread.

required

register_for_remote_notifications

register_for_remote_notifications() -> None

Register with APNs, to get the device token FCM needs. Call it on the main thread (Kivy's), at each launch. Needs the Push Notifications capability (aps-environment entitlement).

launch_hook_status

launch_hook_status() -> str | None

Whether the launch hook package is in the app, and working.

Returns:

Type Description
str | None

None when the app does not include pyios-firebase-notifications-hook;

str | None

otherwise the hook's status, which starts with "ok" when it is

str | None

keeping launch taps (for example "ok: SDLUIKitSceneDelegate").

set_handlers

set_handlers(
    on_foreground: ForegroundHandler | None = None,
    on_open: OpenHandler | None = None,
    *,
    default_presentation: int = NONE,
) -> None

Call Python when a notification arrives with the app open, and when the user taps one. Call it early (before App.run()).

This makes pyios-firebase the notification center's delegate (replacing any other).

A tap that launches the app (it was not running) is delivered by iOS before a Kivy app's Python starts. With the optional pyios-firebase-notifications-hook package in the app, that tap is kept and passed to on_open here, once the app's event loop runs. Without the hook, a Kivy app does not get it. See launch_hook_status.

Parameters:

Name Type Description Default
on_foreground ForegroundHandler | None

gets the Notification; returns the PresentationOptions to show it with (None or 0: do not show).

None
on_open OpenHandler | None

gets the Notification and the action identifier (DEFAULT_ACTION for a tap on the notification).

None
default_presentation int

the options when there is no on_foreground.

NONE