Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1370,6 +1370,21 @@ deliver a test payload to it. Data-only (silent) messages go to the app
delegate, which a Kivy app does not own in Python: send the data with a
notification instead.

**A tap that launches a closed Kivy app.** iOS delivers that tap before a Kivy
app's Python starts, so `on_open` cannot get it by itself. Add the small
optional
[pyios-firebase-notifications-hook](https://github.com/PySimpleObjC/pyios-firebase-notifications-hook)
Swift package: it keeps the tap, and `set_handlers(on_open=...)` delivers it,
with no code change. `notifications.launch_hook_status()` tells whether it is
in the app. Taps while the app is open or in the background need nothing.

```toml
[tool.kivy.ios.native.swift_packages.PyiosFirebaseNotificationsHook]
url = "https://github.com/PySimpleObjC/pyios-firebase-notifications-hook.git"
requirement = { from = "0.1.0" }
products = ["PyiosFirebaseNotificationsHook"]
```

---

## Performance Monitoring
Expand Down Expand Up @@ -1758,6 +1773,7 @@ by name (`EMAIL_ALREADY_IN_USE`, `WRONG_PASSWORD`, `REQUIRES_RECENT_LOGIN`,
| An Analytics event does not show up | It may take up to a day in reports: use DebugView (`-FIRDebugEnabled`) to see events at once |
| Crashlytics shows no crash | Crashlytics does not report while the debugger is attached: launch the app from the Home screen, crash, then launch it again to send |
| Performance traces or HTTP metrics do nothing | `trace.active` is `False`: data collection is off (`data_collection_enabled`, or `firebase_performance_collection_enabled` in `Info.plist`) |
| Tapping a notification opens a closed Kivy app, but `on_open` is not called | Add the pyios-firebase-notifications-hook package (see Cloud Messaging); `notifications.launch_hook_status()` is `None` without it |
| No FCM token | On a device: the push capability and an APNs key in the console are needed. FCM does not work in the Simulator |
| Remote Config values never change | `minimum_fetch_interval` (12 h by default) has not passed, or you fetched but did not `activate` |
| A query fails with an index error | Open the link in the error message and create the index |
Expand Down
11 changes: 9 additions & 2 deletions docs/getting-started/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Every app needs the base: `GoogleService-Info.plist` in the bundle, the
| [App Check](../app-check/index.md#app-configuration) | `FirebaseAppCheck` | The App Attest entitlement |
| [Analytics](../analytics/index.md#app-configuration) | `FirebaseAnalytics` | |
| [Crashlytics](../crashlytics/index.md#app-configuration) | `FirebaseCrashlytics` | The dSYM upload (Release builds make them; kivyforge: `upload-symbols` from the archive) |
| [Cloud Messaging](../messaging/index.md#app-configuration) | `FirebaseMessaging` | The `aps-environment` entitlement, `UIBackgroundModes` |
| [Cloud Messaging](../messaging/index.md#app-configuration) | `FirebaseMessaging` | The `aps-environment` entitlement, `UIBackgroundModes`; in Kivy, the launch hook package (optional) |
| [Performance Monitoring](../performance/index.md#app-configuration) | `FirebasePerformance` | |

## Everything together
Expand Down Expand Up @@ -58,6 +58,12 @@ Every app needs the base: `GoogleService-Info.plist` in the bundle, the
requirement = { from = "10.1.0" }
products = ["GoogleSignIn"]

# --- Messaging, Kivy: the tap that launches a closed app reaches on_open -----
[tool.kivy.ios.native.swift_packages.PyiosFirebaseNotificationsHook]
url = "https://github.com/PySimpleObjC/pyios-firebase-notifications-hook.git"
requirement = { from = "0.1.0" }
products = ["PyiosFirebaseNotificationsHook"]

[tool.kivy.ios.native.swift_packages.facebook-ios-sdk]
url = "https://github.com/facebook/facebook-ios-sdk.git"
requirement = { from = "19.0.1" }
Expand Down Expand Up @@ -103,7 +109,8 @@ Every app needs the base: `GoogleService-Info.plist` in the bundle, the
1. **File > Add Package Dependencies...**:
- `https://github.com/firebase/firebase-ios-sdk.git`: pick the products you use;
- `https://github.com/google/GoogleSignIn-iOS`: `GoogleSignIn` (Google Sign-In);
- `https://github.com/facebook/facebook-ios-sdk.git`: `FacebookLogin` (Facebook Login).
- `https://github.com/facebook/facebook-ios-sdk.git`: `FacebookLogin` (Facebook Login);
- `https://github.com/PySimpleObjC/pyios-firebase-notifications-hook.git`: `PyiosFirebaseNotificationsHook` (Kivy: notification taps that launch the app).
2. **Build Settings**: add `-ObjC` to *Other Linker Flags*; set *Debug Information Format* to *DWARF with dSYM File*.
3. Add `GoogleService-Info.plist` (and `RemoteConfigDefaults.plist`) to the app target.
4. **Info**: the URL types (the `REVERSED_CLIENT_ID`, `fb<APP_ID>`), the Facebook keys, `UIBackgroundModes` with `remote-notification`, and any optional keys.
Expand Down
12 changes: 12 additions & 0 deletions docs/messaging/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,12 @@ them all in one `products`; see [App configuration](../getting-started/configura
# optional: no token until you ask; register with the installation ID
# FirebaseMessagingAutoInitEnabled = false
# FirebaseMessagingInstallationIdEnabled = true

# Kivy: the tap that launches a closed app reaches on_open (optional)
[tool.kivy.ios.native.swift_packages.PyiosFirebaseNotificationsHook]
url = "https://github.com/PySimpleObjC/pyios-firebase-notifications-hook.git"
requirement = { from = "0.1.0" }
products = ["PyiosFirebaseNotificationsHook"]
```

=== "Xcode (kivy-ios, Briefcase)"
Expand All @@ -88,10 +94,16 @@ them all in one `products`; see [App configuration](../getting-started/configura
3. Add `GoogleService-Info.plist` to the app target.
4. **Signing & Capabilities**: *Push Notifications*, and *Background Modes > Remote notifications*.
5. Optional, in **Info**: `FirebaseMessagingAutoInitEnabled` = `NO`, `FirebaseMessagingInstallationIdEnabled` = `YES`.
6. Kivy (kivy-ios), optional: add the `https://github.com/PySimpleObjC/pyios-firebase-notifications-hook.git` package (product `PyiosFirebaseNotificationsHook`), so a tap that launches the closed app reaches `on_open` ([Notifications](notifications.md#when-the-app-is-closed)).

!!! note
Upload an APNs authentication key in the console (**Project settings > Cloud Messaging**).

!!! tip "Kivy: taps that launch the app"
Without the `PyiosFirebaseNotificationsHook` package, a Kivy app still
opens when a notification is tapped while it is closed, but `on_open` does
not get that tap. See [When the app is closed](notifications.md#when-the-app-is-closed).


## The registration token

Expand Down
77 changes: 73 additions & 4 deletions docs/messaging/notifications.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ from pyios_firebase.messaging.notifications import AuthorizationOptions, Present

## Set the handlers first

Set them **early**, before `App.run()`: a tap that launched the app is
delivered right after start-up, and is lost if no handler is there yet.
Set them **early**, before `App.run()`. In a Kivy app, also add the
[launch hook](#when-the-app-is-closed) to get the tap that opens a closed app.

```python
def on_foreground(notification):
Expand Down Expand Up @@ -44,6 +44,74 @@ and are not shown by default. The handlers run on the main thread.
`set_handlers` makes pyios-firebase the notification center's delegate,
replacing any other.

## When the app is closed

What `on_open` gets depends on whether the app was running when the user
tapped:

| The app was... | The tap opens the app | `on_open` gets the notification |
|---|---|---|
| Open (in front) | (it is open) | Yes |
| In the background | Yes | Yes |
| **Closed** (not running), BeeWare / Toga | Yes | Expected, with `set_handlers` in `startup()`: Python starts before launch there (not tested yet) |
| **Closed** (not running), **Kivy** | Yes | **Only with the launch hook below** |

**Why Kivy needs a hook.** When a tap launches the app, iOS delivers it
*during* launch. A Kivy app's Python starts only *after* launch (SDL starts the
interpreter), so no handler exists yet: iOS drops the tap
(`response-not-possible` in the system log). The app opens, but cannot know
which notification was tapped. No Python code can run early enough to catch
it.

### The launch hook

[pyios-firebase-notifications-hook](https://github.com/PySimpleObjC/pyios-firebase-notifications-hook)
is a tiny optional Swift package (one Objective-C file). It starts before
Python, sets a notification handler before launch ends, and keeps the tap.
`set_handlers(on_open=...)` then passes it to your `on_open`, as soon as the
app's event loop runs. **You write no new code**: add the package, and keep
calling `set_handlers`.

=== "kivyforge (pyproject.toml)"

```toml title="pyproject.toml"
[tool.kivy.ios.native.swift_packages.PyiosFirebaseNotificationsHook]
url = "https://github.com/PySimpleObjC/pyios-firebase-notifications-hook.git"
requirement = { from = "0.1.0" }
products = ["PyiosFirebaseNotificationsHook"]
```

=== "Xcode (kivy-ios)"

**File > Add Package Dependencies...**, enter
`https://github.com/PySimpleObjC/pyios-firebase-notifications-hook.git`, and
add the `PyiosFirebaseNotificationsHook` product to the app target.

```python
from pyios_firebase.messaging import notifications

notifications.set_handlers(on_open=on_open) # before App.run(), as always
print(notifications.launch_hook_status()) # "ok: SDLUIKitSceneDelegate"
```

| `launch_hook_status()` | Means |
|---|---|
| `None` | The hook is not in the app: a tap that launches a Kivy app does not reach `on_open` |
| `"ok: SDLUIKitSceneDelegate"` (or another class) | The hook is keeping launch taps |

Good to know:

- The `Notification` is the same as for any other tap: title, body, data, FCM
message ID, identifier and date.
- Without `on_open` yet, the tap stays in the hook until a `set_handlers` call
with one.
- For taps the hook kept, pyios-firebase also tells Firebase Messaging the
notification was opened (for its statistics), once Firebase is configured.
- The hook never replaces a notification handler your app set itself. Toga
apps should not need it (see the table).
- Tested end to end in the iOS Simulator: the app is closed, a notification is
pushed, the banner is tapped, and `on_open` gets its data.

## Ask permission

```python
Expand Down Expand Up @@ -110,8 +178,9 @@ Data sent with `data={...}` from the server arrives as keys of
!!! warning "Data-only messages"
Data-only (silent) messages go to the app delegate's
`application:didReceiveRemoteNotification:fetchCompletionHandler:`,
which belongs to Kivy's (SDL) or Toga's native code, not to Python. Send
data **with** a notification, or read it when the user opens the app.
which belongs to the app's native code (SDL's in a Kivy app), not to
Python. Send data **with** a notification, or read it when the user opens
the app.

Images in notifications need a *Notification Service Extension*, a separate
native target (Swift or Objective-C): not something Python can provide.
Expand Down
7 changes: 7 additions & 0 deletions e2e/ios/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,13 @@ url = "https://github.com/facebook/facebook-ios-sdk.git"
requirement = { from = "19.0.1" }
products = ["FacebookLogin"]

# Keeps the notification tap that launches the app until Python can take it
# (pyios_firebase.messaging.notifications.set_handlers delivers it to on_open)
[tool.kivy.ios.native.swift_packages.PyiosFirebaseNotificationsHook]
url = "https://github.com/PySimpleObjC/pyios-firebase-notifications-hook.git"
requirement = { from = "0.1.0" }
products = ["PyiosFirebaseNotificationsHook"]

[tool.kivy.ios.xcode.build_settings]
OTHER_LDFLAGS = "$(inherited) -ObjC"

Expand Down
22 changes: 21 additions & 1 deletion e2e/ios/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
``E2E_CRASH_AT_END=1``: crash on purpose after the results (Crashlytics).
``E2E_PHASE=after-crash``: only the Crashlytics checks of that crash, written
to ``Documents/pyios-e2e-results-after-crash.json``.
``E2E_PHASE=notification-permission``: ask for full notification permission.
No ``E2E_PHASE`` (a launch from a tapped notification): idle; ``on_open``
records the tap (notification_open.py).

No GoogleService-Info.plist: Firebase is configured in code for the offline
``demo-pyios-firebase`` project, which only the emulator serves.
Expand All @@ -32,7 +35,9 @@
STORAGE_BUCKET = "demo-pyios-firebase.appspot.com"
DATABASE_URL = "https://demo-pyios-firebase-default-rtdb.firebaseio.com"
DATABASE_EMULATOR_HOST = os.environ.get("FIREBASE_DATABASE_EMULATOR_HOST", "127.0.0.1:9000")
PHASE = os.environ.get("E2E_PHASE", "main")
# no E2E_PHASE: launched by a tapped notification (iOS passes no environment),
# so do nothing but record the tap (notification_open.py)
PHASE = os.environ.get("E2E_PHASE", "idle")
CRASH_AT_END = os.environ.get("E2E_CRASH_AT_END") == "1"
RESULTS = os.path.join(
os.path.expanduser("~/Documents"),
Expand Down Expand Up @@ -97,6 +102,16 @@ def build(self):
return scroll

def on_start(self):
if PHASE == "idle":
self.label.text = "pyios-firebase e2e\nlaunched without E2E_PHASE (a notification tap?)"
print("PYIOS-E2E IDLE", flush=True)
return
if PHASE == "notification-permission":
from notification_open import ask_permission

self.label.text = "pyios-firebase e2e\nasking for notification permission"
ask_permission()
return
try:
os.remove(RESULTS)
except FileNotFoundError:
Expand Down Expand Up @@ -205,5 +220,10 @@ def finish(self, report, dumps=None):


if __name__ == "__main__":
# before App.run(), at every launch, as an app must: a tap that launched the
# app is delivered right after start-up
from notification_open import install

install()
E2EApp().run()
sys.exit(0)
5 changes: 4 additions & 1 deletion e2e/ios/src/messaging_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,10 @@ def check() -> None:
expect(notification.date is not None, "date")
t.passed()

notifications.set_handlers(on_foreground=on_foreground)
# keep recording taps (notification_open.py): set_handlers replaces both
from notification_open import install

install(on_foreground=on_foreground)
payload = {
"aps": {"alert": {"title": "Sale", "body": "50% off today"}, "badge": 3},
"gcm.message_id": message_id,
Expand Down
67 changes: 67 additions & 0 deletions e2e/ios/src/notification_open.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"""Notifications tapped while the app is closed: the app records what ``on_open``
gets, and ``run_ios_e2e.sh`` checks it.

A notification tapped while the app is not running launches the app with no
environment variables, so ``install()`` runs at every launch, before
``App.run()``, as a real app's ``set_handlers`` call would.

The ``notification-permission`` phase asks for full permission (alert, badge,
sound), so that banners show on the home screen; the script taps "Allow".
"""

from __future__ import annotations

import json
import os
import time
from typing import Any

from pyios_firebase.messaging import notifications
from pyios_firebase.messaging.notifications import AuthorizationOptions

DOCUMENTS = os.path.expanduser("~/Documents")
OPENED = os.path.join(DOCUMENTS, "pyios-e2e-notification-open.json")
PERMISSION = os.path.join(DOCUMENTS, "pyios-e2e-notification-permission.json")

LAUNCHED_AT = time.time()


def _write(path: str, value: dict[str, Any]) -> None:
with open(path + ".tmp", "w") as f:
json.dump(value, f)
os.replace(path + ".tmp", path) # the host polls for this file


def record_open(notification: notifications.Notification, action: str) -> None:
"""``on_open``: write what the tap delivered, for the script to check."""
_write(OPENED, {
"title": notification.title,
"body": notification.body,
"data": {k: v for k, v in notification.data.items() if k != "aps"},
"message_id": notification.message_id,
"action": action,
"seconds_after_launch": round(time.time() - LAUNCHED_AT, 2),
})
print(f"PYIOS-E2E OPENED {notification.title!r} action={action}", flush=True)


def install(**handlers: Any) -> None:
"""``set_handlers`` with the recorder as ``on_open``.

Args:
**handlers: other handlers (for example ``on_foreground``).
"""
notifications.set_handlers(on_open=record_open, **handlers)


def ask_permission() -> None:
"""The ``notification-permission`` phase: ask for full permission."""

def answered(granted: bool, error: Any) -> None:
_write(PERMISSION, {"granted": bool(granted), "error": None if error is None else str(error)})
print(f"PYIOS-E2E PERMISSION granted={granted}", flush=True)

notifications.request_permission(
AuthorizationOptions.ALERT | AuthorizationOptions.BADGE | AuthorizationOptions.SOUND,
answered,
)
Loading
Loading