From 2a2a3470c320f8ef37754b5d11960f8bb30e36ea Mon Sep 17 00:00:00 2001 From: Houssem Eddine BENABDALLAH Date: Thu, 19 Nov 2026 05:54:23 +0100 Subject: [PATCH] Add arrival notifications with region monitoring of the 20 nearest places --- README.md | 19 +- nativephp.json | 17 +- resources/android/BashoFunctions.kt | 10 ++ resources/ios/BSHArrivalMonitor.swift | 207 ++++++++++++++++++++++ resources/ios/BSHNotificationCenter.swift | 39 +++- resources/ios/BashoFunctions.swift | 33 ++++ src/Arrival.php | 48 +++++ src/Basho.php | 10 ++ src/Events/ArrivalsFailed.php | 23 +++ src/Facades/Basho.php | 2 + tests/BridgeContractTest.php | 24 +++ tests/ManifestTest.php | 11 +- 12 files changed, 426 insertions(+), 17 deletions(-) create mode 100644 resources/ios/BSHArrivalMonitor.swift create mode 100644 src/Arrival.php create mode 100644 src/Events/ArrivalsFailed.php diff --git a/README.md b/README.md index bebac0f..3135a28 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,7 @@ Location and local notifications for [NativePHP Mobile](https://nativephp.com) v - **One-shot position**: ask for the "when in use" permission if needed, then get one fix (latitude, longitude, accuracy) as an event. - **Local notifications**: schedule a notification at a given time, cancel it, and open a route of the app when it is tapped, even from a cold start. - -Geofencing is planned. +- **Arrival notifications**: watch places and post a notification on arriving at one, also when the app is closed (geofencing, "Always" permission). > Status: v0.1, experimental. @@ -15,6 +14,7 @@ Geofencing is planned. |---|---|---| | `Basho.CurrentPosition` | yes (CoreLocation) | yes (`LocationManager`); the first call without permission shows the system dialog and fails with `permission_requested` | | `Basho.ScheduleNotification`, `Basho.CancelNotifications` | yes (`UNUserNotificationCenter`) | not yet: scheduling fails with `unsupported` | +| `Basho.MonitorArrivals` | yes (CoreLocation region monitoring) | not yet: fails with `ArrivalsFailed` `unsupported` | ## Installation @@ -30,7 +30,7 @@ For local development, add a path repository to the app's `composer.json`: "repositories": [{ "type": "path", "url": "../nativephp-basho" }] ``` -The plugin adds `NSLocationWhenInUseUsageDescription` to `Info.plist` (in English, with a French translation written when the app lists `fr` in `nativephp.supported_locales`) and the coarse and fine location permissions to the Android manifest. +The plugin adds `NSLocationWhenInUseUsageDescription` and `NSLocationAlwaysAndWhenInUseUsageDescription` to `Info.plist` (in English, with a French translation written when the app lists `fr` in `nativephp.supported_locales`) and the coarse and fine location permissions to the Android manifest. ## Usage @@ -75,6 +75,18 @@ The first `schedule()` asks for the notification permission. Scheduling again wi On iOS the plugin becomes the `UNUserNotificationCenter` delegate at launch (`ios.init_function`). Another plugin that sets this delegate, such as a push notification plugin, would replace it. +### Arrival notifications + +```php +Basho::monitorArrivals([ + new Arrival('place-3', latitude: 48.85837, longitude: 2.29448, radius: 100, title: 'Kitchen', body: '2 notes here', url: '/places/3'), +]); +``` + +Each call replaces the whole list; an empty list stops monitoring. The first non-empty list asks for the Always location permission and the notification permission. Entering a place's circle posts its notification right away, also when the app is closed: iOS relaunches the app in the background and the plugin posts the notification natively, from the list it saved, without PHP. Tapping it opens its `url` like any other notification. + +iOS monitors 20 regions at most per app: the plugin monitors the 20 places nearest to the last known position and refreshes them on significant location changes. Precision is about 100 m, and a radius over `maximumRegionMonitoringDistance` is clamped. With only "While Using" permission, entries are reported while the app runs, not when it is closed. + ## Events Every event carries `id`, the request id. @@ -86,6 +98,7 @@ Every event carries `id`, the request id. | `PermissionDenied` | `id` | | `NotificationTapped` | `id`, `url`; dropped when the tap cold-starts the app before PHP is up (the `url` still opens) | | `NotificationFailed` | `id`, `code` (`permission_denied`, `unavailable`, `unsupported`), `message` | +| `ArrivalsFailed` | `code` (`permission_denied`, `unavailable`, `unsupported`), `message`; no `id` | Native errors returned synchronously by the bridge are thrown as `BashoBridgeException`. diff --git a/nativephp.json b/nativephp.json index 9a665de..a329c7a 100644 --- a/nativephp.json +++ b/nativephp.json @@ -18,6 +18,12 @@ "ios": "BashoFunctions.CancelNotifications", "android": "com.alpineronin.nativebasho.BashoFunctions.CancelNotifications", "description": "Remove scheduled and delivered local notifications by id" + }, + { + "name": "Basho.MonitorArrivals", + "ios": "BashoFunctions.MonitorArrivals", + "android": "com.alpineronin.nativebasho.BashoFunctions.MonitorArrivals", + "description": "Replace the watched places: ask for Always location permission, monitor the 20 nearest regions and post a local notification on entering one, also when the app is closed" } ], "events": [ @@ -25,7 +31,8 @@ "AlpineRonin\\NativeBasho\\Events\\PositionFailed", "AlpineRonin\\NativeBasho\\Events\\PermissionDenied", "AlpineRonin\\NativeBasho\\Events\\NotificationTapped", - "AlpineRonin\\NativeBasho\\Events\\NotificationFailed" + "AlpineRonin\\NativeBasho\\Events\\NotificationFailed", + "AlpineRonin\\NativeBasho\\Events\\ArrivalsFailed" ], "android": { "permissions": [ @@ -35,14 +42,16 @@ }, "ios": { "info_plist": { - "NSLocationWhenInUseUsageDescription": "Your position is saved with each place so it can be found again." + "NSLocationWhenInUseUsageDescription": "Your position is saved with each place so it can be found again.", + "NSLocationAlwaysAndWhenInUseUsageDescription": "Your position is checked in the background to tell you when you arrive at a place that has notes." }, "info_plist_localizations": { "fr": { - "NSLocationWhenInUseUsageDescription": "Votre position est enregistrée avec chaque lieu pour le retrouver." + "NSLocationWhenInUseUsageDescription": "Votre position est enregistrée avec chaque lieu pour le retrouver.", + "NSLocationAlwaysAndWhenInUseUsageDescription": "Votre position est vérifiée en arrière-plan pour vous prévenir quand vous arrivez dans un lieu qui a des notes." } }, - "init_function": "BSHNotificationCenter.install", + "init_function": "BSHLaunch.install", "dependencies": { "swift_packages": [], "pods": [] diff --git a/resources/android/BashoFunctions.kt b/resources/android/BashoFunctions.kt index 5cf2fc4..3dce4f5 100644 --- a/resources/android/BashoFunctions.kt +++ b/resources/android/BashoFunctions.kt @@ -97,6 +97,16 @@ object BashoFunctions { } } + class MonitorArrivals(private val activity: FragmentActivity) : BridgeFunction { + override fun execute(parameters: Map): Map { + dispatch(activity, "ArrivalsFailed", JSONObject() + .put("code", "unsupported") + .put("message", "Arrival notifications are not implemented on Android yet.")) + + return BridgeResponse.success(mapOf("count" to 0)) + } + } + class ScheduleNotification(private val activity: FragmentActivity) : BridgeFunction { override fun execute(parameters: Map): Map { val id = parameters["id"] as? String ?: UUID.randomUUID().toString() diff --git a/resources/ios/BSHArrivalMonitor.swift b/resources/ios/BSHArrivalMonitor.swift new file mode 100644 index 0000000..d5d8590 --- /dev/null +++ b/resources/ios/BSHArrivalMonitor.swift @@ -0,0 +1,207 @@ +import Foundation +import CoreLocation + +/// Every launch hook of the plugin, run by `ios.init_function`. +enum BSHLaunch { + static func install() { + BSHNotificationCenter.install() + BSHArrivalMonitor.install() + } +} + +struct BSHArrival: Codable { + let id: String + let latitude: Double + let longitude: Double + let radius: Double + let title: String + let body: String + let url: String? +} + +/// Watches the places sent by PHP and posts their notification on entry. +/// iOS relaunches a closed app in the background to deliver a region entry, +/// before any PHP code runs: the list is kept in UserDefaults and the +/// manager is created at launch so the entry is handled natively. +/// iOS monitors 20 regions at most per app, so only the 20 places nearest to +/// the last known position are monitored, refreshed on significant moves. +final class BSHArrivalMonitor: NSObject, CLLocationManagerDelegate { + static let shared = BSHArrivalMonitor() + + private static let maxRegions = 20 + private static let storageKey = "basho.arrivals" + private static let regionPrefix = "basho.arrival." + + private let manager = CLLocationManager() + private var arrivals: [BSHArrival] + + override init() { + arrivals = Self.load() + super.init() + manager.delegate = self + } + + static func install() { + shared.start() + } + + func replace(_ arrivals: [BSHArrival]) { + self.arrivals = arrivals + Self.save(arrivals) + + guard !arrivals.isEmpty else { + stop() + return + } + + guard CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) else { + fail("unsupported", "Region monitoring is not available on this device.") + return + } + + BSHNotificationCenter.shared.requestAuthorization() + + switch manager.authorizationStatus { + case .notDetermined: + manager.requestAlwaysAuthorization() + + case .authorizedWhenInUse: + manager.requestAlwaysAuthorization() + start() + + case .authorizedAlways: + start() + + default: + fail("permission_denied", "Location access is not allowed.") + } + } + + func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { + guard !arrivals.isEmpty else { + return + } + + switch manager.authorizationStatus { + case .authorizedAlways, .authorizedWhenInUse: + start() + + case .denied, .restricted: + stop() + fail("permission_denied", "Location access is not allowed.") + + default: + break + } + } + + func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { + refreshRegions(near: locations.last) + } + + func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { + guard region.identifier.hasPrefix(Self.regionPrefix) else { + return + } + + let id = String(region.identifier.dropFirst(Self.regionPrefix.count)) + + guard let arrival = arrivals.first(where: { $0.id == id }) else { + return + } + + BSHNotificationCenter.shared.deliver(id: arrival.id, title: arrival.title, body: arrival.body, url: arrival.url) + } + + func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) { + fail("unavailable", error.localizedDescription) + } + + private func start() { + guard !arrivals.isEmpty else { + return + } + + switch manager.authorizationStatus { + case .authorizedAlways, .authorizedWhenInUse: + manager.startMonitoringSignificantLocationChanges() + refreshRegions(near: manager.location) + + default: + break + } + } + + private func stop() { + manager.stopMonitoringSignificantLocationChanges() + + for region in manager.monitoredRegions where region.identifier.hasPrefix(Self.regionPrefix) { + manager.stopMonitoring(for: region) + } + } + + private func refreshRegions(near location: CLLocation?) { + let nearest = arrivals + .map { arrival in (arrival: arrival, distance: location?.distance(from: Self.center(of: arrival)) ?? 0) } + .sorted { $0.distance < $1.distance } + .prefix(Self.maxRegions) + .map { region(for: $0.arrival) } + let wanted = Dictionary(nearest.map { ($0.identifier, $0) }, uniquingKeysWith: { first, _ in first }) + + for region in manager.monitoredRegions where region.identifier.hasPrefix(Self.regionPrefix) { + if let target = wanted[region.identifier], Self.same(region, target) { + continue + } + + manager.stopMonitoring(for: region) + } + + let kept = Set(manager.monitoredRegions.map(\.identifier)) + + for region in wanted.values where !kept.contains(region.identifier) { + manager.startMonitoring(for: region) + } + } + + private func region(for arrival: BSHArrival) -> CLCircularRegion { + let region = CLCircularRegion( + center: CLLocationCoordinate2D(latitude: arrival.latitude, longitude: arrival.longitude), + radius: min(arrival.radius, manager.maximumRegionMonitoringDistance), + identifier: Self.regionPrefix + arrival.id + ) + region.notifyOnEntry = true + region.notifyOnExit = false + + return region + } + + private static func center(of arrival: BSHArrival) -> CLLocation { + CLLocation(latitude: arrival.latitude, longitude: arrival.longitude) + } + + private static func same(_ region: CLRegion, _ target: CLCircularRegion) -> Bool { + guard let circle = region as? CLCircularRegion else { + return false + } + + return abs(circle.center.latitude - target.center.latitude) < 1e-7 + && abs(circle.center.longitude - target.center.longitude) < 1e-7 + && abs(circle.radius - target.radius) < 0.01 + } + + private static func load() -> [BSHArrival] { + guard let data = UserDefaults.standard.data(forKey: storageKey) else { + return [] + } + + return (try? JSONDecoder().decode([BSHArrival].self, from: data)) ?? [] + } + + private static func save(_ arrivals: [BSHArrival]) { + UserDefaults.standard.set(try? JSONEncoder().encode(arrivals), forKey: storageKey) + } + + private func fail(_ code: String, _ message: String) { + BSHEventBus.send("ArrivalsFailed", ["code": code, "message": message]) + } +} diff --git a/resources/ios/BSHNotificationCenter.swift b/resources/ios/BSHNotificationCenter.swift index 8975275..9097424 100644 --- a/resources/ios/BSHNotificationCenter.swift +++ b/resources/ios/BSHNotificationCenter.swift @@ -14,6 +14,32 @@ final class BSHNotificationCenter: NSObject, UNUserNotificationCenterDelegate { } func schedule(id: String, title: String, body: String, at: Date, url: String?) { + let trigger = UNTimeIntervalNotificationTrigger(timeInterval: max(1, at.timeIntervalSinceNow), repeats: false) + + whenAuthorized(id) { + self.add(id: id, title: title, body: body, url: url, trigger: trigger) + } + } + + /// Shows a notification right away, without asking for the permission: + /// it may run in a background launch where no prompt can be shown. + func deliver(id: String, title: String, body: String, url: String?) { + UNUserNotificationCenter.current().getNotificationSettings { settings in + switch settings.authorizationStatus { + case .authorized, .provisional, .ephemeral: + self.add(id: id, title: title, body: body, url: url, trigger: nil) + + default: + self.fail(id, "permission_denied", "Notifications are not allowed.") + } + } + } + + func requestAuthorization() { + whenAuthorized(nil) {} + } + + private func whenAuthorized(_ id: String?, _ then: @escaping () -> Void) { let center = UNUserNotificationCenter.current() center.getNotificationSettings { settings in @@ -21,17 +47,19 @@ final class BSHNotificationCenter: NSObject, UNUserNotificationCenterDelegate { case .notDetermined: center.requestAuthorization(options: [.alert, .sound]) { granted, error in if granted { - self.add(id: id, title: title, body: body, at: at, url: url) - } else { + then() + } else if let id { self.fail(id, "permission_denied", error?.localizedDescription ?? "Notifications are not allowed.") } } case .denied: - self.fail(id, "permission_denied", "Notifications are not allowed.") + if let id { + self.fail(id, "permission_denied", "Notifications are not allowed.") + } default: - self.add(id: id, title: title, body: body, at: at, url: url) + then() } } } @@ -79,7 +107,7 @@ final class BSHNotificationCenter: NSObject, UNUserNotificationCenterDelegate { return URL(string: "basho:/" + route) } - private func add(id: String, title: String, body: String, at: Date, url: String?) { + private func add(id: String, title: String, body: String, url: String?, trigger: UNNotificationTrigger?) { let content = UNMutableNotificationContent() content.title = title content.body = body @@ -89,7 +117,6 @@ final class BSHNotificationCenter: NSObject, UNUserNotificationCenterDelegate { content.userInfo = [Self.urlKey: url] } - let trigger = UNTimeIntervalNotificationTrigger(timeInterval: max(1, at.timeIntervalSinceNow), repeats: false) let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) { error in diff --git a/resources/ios/BashoFunctions.swift b/resources/ios/BashoFunctions.swift index 5d54d06..eae8a82 100644 --- a/resources/ios/BashoFunctions.swift +++ b/resources/ios/BashoFunctions.swift @@ -50,6 +50,39 @@ enum BashoFunctions { return BridgeResponse.success(data: ["ids": ids]) } } + + // MARK: - Basho.MonitorArrivals + + class MonitorArrivals: BridgeFunction { + func execute(parameters: [String: Any]) throws -> [String: Any] { + let arrivals = (parameters["arrivals"] as? [[String: Any]] ?? []).compactMap { item -> BSHArrival? in + guard + let id = item["id"] as? String, + let latitude = (item["latitude"] as? NSNumber)?.doubleValue, + let longitude = (item["longitude"] as? NSNumber)?.doubleValue, + let radius = (item["radius"] as? NSNumber)?.doubleValue + else { + return nil + } + + return BSHArrival( + id: id, + latitude: latitude, + longitude: longitude, + radius: radius, + title: item["title"] as? String ?? "", + body: item["body"] as? String ?? "", + url: item["url"] as? String + ) + } + + DispatchQueue.main.async { + BSHArrivalMonitor.shared.replace(arrivals) + } + + return BridgeResponse.success(data: ["count": arrivals.count]) + } + } } enum BSHEventBus { diff --git a/src/Arrival.php b/src/Arrival.php new file mode 100644 index 0000000..1c5ad25 --- /dev/null +++ b/src/Arrival.php @@ -0,0 +1,48 @@ + $this->id, + 'latitude' => $this->latitude, + 'longitude' => $this->longitude, + 'radius' => $this->radius, + 'title' => $this->title, + 'body' => $this->body, + ]; + + if ($this->url !== null) { + $payload['url'] = $this->url; + } + + return $payload; + } +} diff --git a/src/Basho.php b/src/Basho.php index cc2814f..d0cbbd8 100644 --- a/src/Basho.php +++ b/src/Basho.php @@ -32,4 +32,14 @@ public function cancelNotifications(array $ids): void Bridge::call('Basho.CancelNotifications', ['ids' => array_values($ids)]); } + + /** + * @param list $arrivals + */ + public function monitorArrivals(array $arrivals): void + { + Bridge::call('Basho.MonitorArrivals', [ + 'arrivals' => array_map(fn (Arrival $arrival): array => $arrival->toPayload(), array_values($arrivals)), + ]); + } } diff --git a/src/Events/ArrivalsFailed.php b/src/Events/ArrivalsFailed.php new file mode 100644 index 0000000..19415fe --- /dev/null +++ b/src/Events/ArrivalsFailed.php @@ -0,0 +1,23 @@ + $ids) + * @method static void monitorArrivals(list $arrivals) * * @see \AlpineRonin\NativeBasho\Basho */ diff --git a/tests/BridgeContractTest.php b/tests/BridgeContractTest.php index 642016b..7cfaa76 100644 --- a/tests/BridgeContractTest.php +++ b/tests/BridgeContractTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +use AlpineRonin\NativeBasho\Arrival; +use AlpineRonin\NativeBasho\Events\ArrivalsFailed; use AlpineRonin\NativeBasho\Events\NotificationFailed; use AlpineRonin\NativeBasho\Events\NotificationTapped; use AlpineRonin\NativeBasho\Events\PermissionDenied; @@ -113,3 +115,25 @@ expect($tap->url)->toBe('/places/3') ->and(new NotificationFailed('note-3', 'permission_denied'))->code->toBe('permission_denied'); }); + +it('replaces the monitored arrivals in one call', function () { + Basho::monitorArrivals([ + new Arrival('place-3', 48.85837, 2.29448, 100.0, 'Kitchen', '2 notes here', '/places/3'), + new Arrival('place-4', 45.764, 4.8357, 150.0, 'Office', '1 note here'), + ]); + + $this->bridge->assertCalled('Basho.MonitorArrivals', fn (array $p) => $p === ['arrivals' => [ + ['id' => 'place-3', 'latitude' => 48.85837, 'longitude' => 2.29448, 'radius' => 100.0, 'title' => 'Kitchen', 'body' => '2 notes here', 'url' => '/places/3'], + ['id' => 'place-4', 'latitude' => 45.764, 'longitude' => 4.8357, 'radius' => 150.0, 'title' => 'Office', 'body' => '1 note here'], + ]]); +}); + +it('stops monitoring arrivals with an empty list', function () { + Basho::monitorArrivals([]); + + $this->bridge->assertCalled('Basho.MonitorArrivals', fn (array $p) => $p === ['arrivals' => []]); +}); + +it('builds the arrival failure event from a native payload', function () { + expect(new ArrivalsFailed(...['code' => 'permission_denied', 'message' => 'No']))->code->toBe('permission_denied'); +}); diff --git a/tests/ManifestTest.php b/tests/ManifestTest.php index 20b3353..80f302e 100644 --- a/tests/ManifestTest.php +++ b/tests/ManifestTest.php @@ -42,7 +42,8 @@ }); it('explains why it needs the location on iOS', function () { - expect($this->manifest['ios']['info_plist']['NSLocationWhenInUseUsageDescription'])->not->toBeEmpty(); + expect($this->manifest['ios']['info_plist']['NSLocationWhenInUseUsageDescription'])->not->toBeEmpty() + ->and($this->manifest['ios']['info_plist']['NSLocationAlwaysAndWhenInUseUsageDescription'])->not->toBeEmpty(); }); it('translates every Info.plist text into French', function () { @@ -50,9 +51,11 @@ ->toBe(array_keys($this->manifest['ios']['info_plist'])); }); -it('installs the notification delegate at launch', function () { +it('installs the notification delegate and the arrival monitor at launch', function () { [$class, $method] = explode('.', $this->manifest['ios']['init_function']); - expect($this->swift)->toContain("final class {$class}") - ->and($this->swift)->toContain("static func {$method}()"); + expect($this->swift)->toContain("enum {$class}") + ->and($this->swift)->toContain("static func {$method}()") + ->and($this->swift)->toContain('BSHNotificationCenter.install()') + ->and($this->swift)->toContain('BSHArrivalMonitor.install()'); });