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
19 changes: 16 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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

Expand All @@ -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

Expand Down Expand Up @@ -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.
Expand All @@ -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`.

Expand Down
17 changes: 13 additions & 4 deletions nativephp.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,21 @@
"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": [
"AlpineRonin\\NativeBasho\\Events\\PositionReceived",
"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": [
Expand All @@ -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": []
Expand Down
10 changes: 10 additions & 0 deletions resources/android/BashoFunctions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,16 @@ object BashoFunctions {
}
}

class MonitorArrivals(private val activity: FragmentActivity) : BridgeFunction {
override fun execute(parameters: Map<String, Any>): Map<String, Any> {
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<String, Any>): Map<String, Any> {
val id = parameters["id"] as? String ?: UUID.randomUUID().toString()
Expand Down
207 changes: 207 additions & 0 deletions resources/ios/BSHArrivalMonitor.swift
Original file line number Diff line number Diff line change
@@ -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])
}
}
39 changes: 33 additions & 6 deletions resources/ios/BSHNotificationCenter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,24 +14,52 @@ 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
switch settings.authorizationStatus {
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()
}
}
}
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
Loading
Loading