Repository navigation
extra: Receive remote notifications on iOS with a new push module - #2729
Merged
Merged
Conversation
Some apps need remote notifications, and each push service brings its own SDK. The runtime keeps only generic hooks for them (application events and the handler of notifications NSH did not show); this adds the module apps turn on to use them: `Push` in TSX and `nsh_extra::push` in Rust, behind the `push` feature of `nsh-extra`. The module registers the device and resolves with its token, reports a token that changed, the notifications that arrive in front (shown as the app decided beforehand, since the system asks at once), the presses (the one that launched the app waits for the first listener) and the background deliveries, whose completion the system hears once the listeners settle, or after a short wait when none listens. It removes the delivered notifications of a thread; one goes by its id with `Notifications.close`. Rust code, such as a push service's SDK binding, hears every event with the token's bytes and gets the launch options as the system passed them. The feature adds the `remote-notification` background mode; the `aps-environment` entitlement comes from the provisioning profile, which grants it for its own environment. Elsewhere than a standalone iOS app the module is unavailable.
Review follow-ups for the `push` module:
- The hub's `dispatch` returns only what no VM will get, so a delivery
that VMs took is no longer reported lost.
- A background delivery carries its arrival: its wait for a listener
and its listeners' deadline count from it, also when a VM gives it
back, so the system always hears within the budget.
- `DeviceToken` is opaque (`as_str`, the string the push service takes,
and `as_bytes`); `register()` and `token()` give `{ token }` in TS,
and Rust's `device_token()` is `token()`.
- Notifications in front show per thread (`setForegroundPresentation`
with `{ threadId }`, `set_thread_presentation`), and Rust code can
decide each one (`set_foreground_presentation_decider`).
- `closeThread` refuses an empty thread, leaves the notifications
`Notifications` showed, and resolves with nothing.
- `launch_options()` goes: `on_application_event` already gives them.
The foreign handler is set once the standalone app launches, a
closing VM gives back what it did not post, and a failed registration
leaves no waiting answer.
- Narrower public surface; CI tests and lints `push`.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
What
A new module of
nsh-extra,push(Pushin TSX,nsh_extra::pushin Rust): remote notifications on iOS, with any push service.register()callsregisterForRemoteNotificationsand resolves with the device token in hex. It rejects with the system's reason when the device is not registered, for example when the app is signed withoutaps-environment. The user's permission stays with the existingNotifications.permission/requestPermission. Registering does not need it.on("token")reports a registration whose token differs from the last one of the run. The first token is included.token()reads the last one.on("notification"): a notification arrived while the app is in front. How it shows is decided ahead of time withsetForegroundPresentation({ banner, list, sound, badge }), because the system asks at once and the main thread never waits for JS.foregroundPresentation()reads it. By default it shows as it does behind, likeNotifications' own.on("press"): the user pressed a notification. The press that launched the app waits for the first listener. At most 16 presses wait.on("background"): a delivery that woke the app or reached it in front (content-available). The system waits for the listeners. A listener returns"newData","noData"or"failed", or a promise of one, within 25 seconds. Nothing returned counts as"noData", and a throw or a timeout counts as"failed". A delivery that came while nothing listened waits 5 seconds for a listener. After that the system hearsnoData.closeThread(threadId)removes the delivered notifications grouped in a thread. It readsgetDeliveredNotificationsand filters bythreadIdentifier, then resolves with how many it removed. One notification is removed by its id with the existingNotifications.close(id), which already removes any delivered request with that identifier. No second API does the same.available()istruein a standalone iOS app. On Android, the desktops, the web and Mac Catalyst it isfalse, and in an app that embeds NSH in its own UIKit app, whose delegate stays its own. ThereregisterandcloseThreadreject withERR_FEATURE_UNAVAILABLE_ON_PLATFORMand nothing panics.userInfoas JSON, through the shareduser_info_json, with theapsdictionary included.How it is built
The module uses only the hooks already on
main. It makes no change outsidensh-extra.#[native_module]entry runs on the main thread beforerun_app. There, on the first run only,pushcallsnsh_platform_ios::on_application_event, for the launch, the token, failures and background deliveries with theirFetchCompletion. It also callsnsh_platform_apple::notifications::set_foreign_handler, for foreground presentation and presses, the cold-start press included.Launchedis what makes the module available. An app that embeds NSH never delivers it, so there the module reports itself unavailable. Without that,register()would never resolve.Push.onsubscribes once with a channel and says which events it listens to, so presses wait for the first VM that listens topress. A background delivery shares one completion among the VMs listening. The system hears once the last clone goes, with the most significant result (newData>failed>noData).pushon, the module owns the single foreign-notification handler. The iOS guide now says that an app crate listens throughnsh_extra::push::on_eventrather than setting its own handler, which would replace the module's. The core already warns when that happens.Packaging
[package.metadata.nsh.features.push.ios.infoPlist]declaresUIBackgroundModes = ["remote-notification"], which the CLI joins with the app's own modes.aps-environmentis deliberately not declared. For devices,nsh package --target iossigns with the entitlements the provisioning profile grants (Profile::entitlementsstarts from them), and a push-enabled profile grantsaps-environmentfor its own environment:developmentorproduction. A fixed value in the crate would be checked bygrantagainst every profile and would fail under the profile of the other environment. An app that wants it elsewhere setsios.entitlementsinnsh.json.Docs: the nshm guide's
nsh-extrasection gets a Push part, and the iOS guide notes thatpushowns the foreign handler (English and zh-CN). The crate docs' module table and the repository map are updated too.Why
The maintainers decided that remote notifications stay out of the core and come as an optional module, with the core providing the generic hooks. This is that module. It is not tied to any push service: a push service's SDK binding can build on the Rust API, which gives it the token's bytes, every event and the raw launch options.
Public API
nsh-extra(featurepush), TS:Push.available(): Promise<boolean>: whether remote notifications work here.Push.register(): Promise<string>: registers the device and resolves with its token in hex.Push.token(): string | null: the last token of this run.Push.foregroundPresentation(): PushPresentation/Push.setForegroundPresentation(presentation: PushPresentationOptions): void: how notifications in front show ({ banner, list, sound, badge }; what the options leave out shows).Push.closeThread(threadId: string): Promise<number>: removes a thread's delivered notifications; resolves with the count.Push.on("token", (token: PushToken) => void): () => void:{ token }.Push.on("notification" | "press", (notification: PushNotification) => void): () => void:{ id, threadId, payload }.Push.on("background", (background: PushBackground) => void | BackgroundResult | Promise<void | BackgroundResult>): () => void:{ threadId, payload };BackgroundResultis"newData" | "noData" | "failed".nsh_extra::push, Rust:async fn available() -> bool,async fn register() -> Result<DeviceToken, PushError>,fn device_token() -> Option<DeviceToken>: the same from Rust.fn foreground_presentation() -> ForegroundPresentation,fn set_foreground_presentation(ForegroundPresentation):ForegroundPresentation { banner, list, sound, badge }(non-exhaustive,Default/SHOWNall true, builder methods).async fn close_thread(String) -> Result<usize, PushError>: removes a thread's delivered notifications.fn on_event(impl Fn(&PushEvent<'_>) + Send + Sync + 'static): a Rust observer of every event on the main thread.PushEvent(non-exhaustive) isToken(&DeviceToken),RegistrationFailed(&PushError),Notification(&RemoteNotification),Background { notification, completion: &BackgroundCompletion }orPress(&RemoteNotification).#[cfg(target_os = "ios")] fn launch_options() -> Option<NonNull<c_void>>: the launch options'NSDictionary *, kept for the life of the process, for an SDK that takes them as they are.DeviceToken(new,as_bytes,to_hex,Display): the token.RemoteNotification { id, thread_id, payload: JsonValue }(non-exhaustive;new,background(payload), which takes the thread fromaps.thread-id).BackgroundResult { NewData, NoData, Failed }(merge), andBackgroundCompletion(new(finish),set_result,Clone,Send): the system hears once the last clone is dropped.PushError { code, message }(failed,unavailable),UNAVAILABLE,BACKGROUND_WAIT(5 s),BACKGROUND_LIMIT(25 s).Push,PushPresentation,PushPresentationOptions,PushToken,PushNotification,PushBackground) arepub(crate). They are not Rust API.nsh-extraCargo.toml:push.[package.metadata.nsh.features.push.ios.infoPlist] UIBackgroundModes = ["remote-notification"].How to Test
Device not verified. No APNs delivery, token or press was exercised on a device or simulator. Only compile checks ran on this machine. The unit tests are written but were not run.
Ran:
cargo check -p nsh-extrawith--features push,--features push --tests,--features camera,push --testsand--tests(host).cargo check -p nsh-extra --target aarch64-apple-iosand--target aarch64-apple-ios-macabi, each with--features push,--features push --testsand--features camera,push.cargo check -p nsh-extra --target aarch64-linux-android --features push --testsand--target wasm32-unknown-unknown --features push.cargo +nightly fmt -p nsh-extra --check,python3 .github/ci/paths.py.Not run (for CI or a maintainer):
cargo test -p nsh-extra --features push(also withcamera,push):tokens_are_hexadecimal,a_background_delivery_takes_its_thread_from_the_payload,presentation_options_leave_out_what_shows,errors_keep_their_codes,results_combine_by_significance,the_system_hears_once_when_the_last_clone_goes,threads_are_filtered_by_identifier,presses_wait_for_the_first_listener_in_order,at_most_sixteen_presses_wait,notifications_in_front_do_not_wait,a_background_delivery_waits_a_while_for_a_listener,every_listening_vm_shares_a_background_completion,only_vms_listening_to_a_kind_get_it,a_token_is_reported_when_it_changes,rust_observers_hear_every_event,the_foreground_presentation_is_set_before_notifications_come,there_are_no_remote_notifications_off_ios,the_set_declares_push.cargo clippy -p nsh-extra --all-targets --features camera,push, and the Catalyst clippy command withnsh-extra/pushadded.Push.register()returns a token. A push sent with that token shows in front assetForegroundPresentationsays and reacheson("notification"). Pressing it from a killed app reacheson("press"). Acontent-availablepush reacheson("background"), and the completion is called.closeThreadremoves only that thread. In the simulator,xcrun simctl pushwith an.apnsfile covers the foreground, press and background paths.CI note:
rust-app.ymltests and lintsnsh-extrawithcameraonly. Addingpushto that feature list would run these tests in CI. This PR leaves the workflow as it is.Checklist
cargo test --workspace,cargo +nightly fmt --alland clippy (including the Catalyst and Android runs for platform code).tests/compat/(cargo xtask compat).examples/gallerydemos on iOS and Android (if the change is visible or platform-specific).