Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable background geolocation updates #1889

Draft
wants to merge 1 commit into
base: v2
Choose a base branch
from
Draft
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
9 changes: 6 additions & 3 deletions plugins/geolocation/guest-js/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ export type PositionOptions = {
}

export async function watchPosition(
options: PositionOptions,
options: PositionOptions & {requestUpdatesInBackground?: boolean},
cb: (location: Position | null, error?: string) => void
): Promise<number> {
const channel = new Channel<Position | string>()
Expand All @@ -106,6 +106,7 @@ export async function watchPosition(
}
await invoke('plugin:geolocation|watch_position', {
options,
requestUpdatesInBackground: options.requestUpdatesInBackground ?? false,
channel
})
return channel.id
Expand All @@ -130,9 +131,11 @@ export async function checkPermissions(): Promise<PermissionStatus> {
}

export async function requestPermissions(
permissions: PermissionType[] | null
permissions: PermissionType[] | null,
requestUpdatesInBackground: boolean = false
): Promise<PermissionStatus> {
return await invoke('plugin:geolocation|request_permissions', {
permissions
permissions,
requestUpdatesInBackground
})
}
57 changes: 51 additions & 6 deletions plugins/geolocation/ios/Sources/GeolocationPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,28 @@ class GetPositionArgs: Decodable {

class WatchPositionArgs: Decodable {
let options: GetPositionArgs
let request_updates_in_background: Bool
let channel: Channel
}

class ClearWatchArgs: Decodable {
let channelId: UInt32
}

enum PermissionType: String, Decodable {
case location
case coarseLocation
}

class RequestPermissionsArgs: Decodable {
let permissions: [PermissionType]
let requestUpdatesInBackground: Bool
}

class GeolocationPlugin: Plugin, CLLocationManagerDelegate {
private let locationManager = CLLocationManager()
private var isUpdatingLocation: Bool = false
private var backgroundUpdatesRequested: Bool = false
private var permissionRequests: [Invoke] = []
private var positionRequests: [Invoke] = []
private var watcherChannels: [Channel] = []
Expand Down Expand Up @@ -61,6 +73,8 @@ class GeolocationPlugin: Plugin, CLLocationManagerDelegate {
@objc public func watchPosition(_ invoke: Invoke) throws {
let args = try invoke.parseArgs(WatchPositionArgs.self)

self.backgroundUpdatesRequested = args.request_updates_in_background;

self.watcherChannels.append(args.channel)

DispatchQueue.main.async {
Expand All @@ -70,12 +84,28 @@ class GeolocationPlugin: Plugin, CLLocationManagerDelegate {
self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
}



// TODO: Use the authorizationStatus instance property with locationManagerDidChangeAuthorization(_:) instead.
if CLLocationManager.authorizationStatus() == .notDetermined {
self.locationManager.requestWhenInUseAuthorization()
if self.backgroundUpdatesRequested {
self.locationManager.requestAlwaysAuthorization()
} else {
self.locationManager.requestWhenInUseAuthorization()
}
} else {
self.locationManager.startUpdatingLocation()
self.isUpdatingLocation = true
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse && self.backgroundUpdatesRequested {
self.locationManager.requestAlwaysAuthorization()
} else {
self.locationManager.startUpdatingLocation()
self.isUpdatingLocation = true
// Enable background updates if enabled
if self.backgroundUpdatesRequested {
self.locationManager.allowsBackgroundLocationUpdates = true
self.locationManager.pausesLocationUpdatesAutomatically = false
self.locationManager.showsBackgroundLocationIndicator = true
}
}
}
}

Expand Down Expand Up @@ -125,9 +155,19 @@ class GeolocationPlugin: Plugin, CLLocationManagerDelegate {
// TODO: Use the authorizationStatus instance property with locationManagerDidChangeAuthorization(_:) instead.
if CLLocationManager.authorizationStatus() == .notDetermined {
self.permissionRequests.append(invoke)

DispatchQueue.main.async {
self.locationManager.requestWhenInUseAuthorization()
do {
let args = try invoke.parseArgs(RequestPermissionsArgs.self)

DispatchQueue.main.async {
self.locationManager.requestWhenInUseAuthorization()
if args.requestUpdatesInBackground {
// Request background permission if requested
self.locationManager.requestAlwaysAuthorization()
self.backgroundUpdatesRequested = true
}
}
} catch {
invoke.reject(error.localizedDescription)
}
} else {
checkPermissions(invoke)
Expand Down Expand Up @@ -224,6 +264,11 @@ class GeolocationPlugin: Plugin, CLLocationManagerDelegate {
private func stopUpdating() {
self.locationManager.stopUpdatingLocation()
self.isUpdatingLocation = false
if self.backgroundUpdatesRequested {
self.locationManager.allowsBackgroundLocationUpdates = false
self.locationManager.pausesLocationUpdatesAutomatically = true
self.locationManager.showsBackgroundLocationIndicator = false
}
}

private func convertLocation(_ location: CLLocation) -> JsonObject {
Expand Down
3 changes: 3 additions & 0 deletions plugins/geolocation/permissions/default.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[default]
description = "Default permissions for the plugin"
permissions = ["allow-request-permissions", "allow-check-permissions", "allow-clear-watch", "allow-watch-position", "allow-get-current-position"]
6 changes: 4 additions & 2 deletions plugins/geolocation/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ pub(crate) async fn get_current_position<R: Runtime>(
pub(crate) async fn watch_position<R: Runtime>(
app: AppHandle<R>,
options: PositionOptions,
request_updates_in_background: bool,
channel: Channel,
) -> Result<()> {
app.geolocation().watch_position_inner(options, channel)
app.geolocation().watch_position_inner(options, channel, request_updates_in_background)
}

#[command]
Expand All @@ -42,6 +43,7 @@ pub(crate) async fn check_permissions<R: Runtime>(app: AppHandle<R>) -> Result<P
pub(crate) async fn request_permissions<R: Runtime>(
app: AppHandle<R>,
permissions: Option<Vec<PermissionType>>,
request_updates_in_background: bool,
) -> Result<PermissionStatus> {
app.geolocation().request_permissions(permissions)
app.geolocation().request_permissions(permissions, request_updates_in_background)
}
5 changes: 4 additions & 1 deletion plugins/geolocation/src/desktop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ impl<R: Runtime> Geolocation<R> {
pub fn watch_position<F: Fn(WatchEvent) + Send + Sync + 'static>(
&self,
options: PositionOptions,
request_updates_in_background: bool,
callback: F,
) -> crate::Result<u32> {
let channel = Channel::new(move |event| {
Expand All @@ -51,14 +52,15 @@ impl<R: Runtime> Geolocation<R> {
});
let id = channel.id();

self.watch_position_inner(options, channel)?;
self.watch_position_inner(options, request_updates_in_background, channel)?;

Ok(id)
}

pub(crate) fn watch_position_inner(
&self,
_options: PositionOptions,
_request_updates_in_background: bool,
_callback_channel: Channel,
) -> crate::Result<()> {
Ok(())
Expand All @@ -75,6 +77,7 @@ impl<R: Runtime> Geolocation<R> {
pub fn request_permissions(
&self,
_permissions: Option<Vec<PermissionType>>,
_request_updates_in_background: bool,
) -> crate::Result<PermissionStatus> {
Ok(PermissionStatus::default())
}
Expand Down
19 changes: 16 additions & 3 deletions plugins/geolocation/src/mobile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ impl<R: Runtime> Geolocation<R> {
pub fn watch_position<F: Fn(WatchEvent) + Send + Sync + 'static>(
&self,
options: PositionOptions,
request_updates_in_background: bool,
callback: F,
) -> crate::Result<u32> {
let channel = Channel::new(move |event| {
Expand All @@ -66,18 +67,26 @@ impl<R: Runtime> Geolocation<R> {
});
let id = channel.id();

self.watch_position_inner(options, channel)?;
self.watch_position_inner(options, request_updates_in_background, channel)?;

Ok(id)
}

pub(crate) fn watch_position_inner(
&self,
options: PositionOptions,
request_updates_in_background: bool,
channel: Channel,
) -> crate::Result<()> {
self.0
.run_mobile_plugin("watchPosition", WatchPayload { options, channel })
.run_mobile_plugin(
"watchPosition",
WatchPayload {
options,
channel,
request_updates_in_background,
},
)
.map_err(Into::into)
}

Expand All @@ -96,11 +105,15 @@ impl<R: Runtime> Geolocation<R> {
pub fn request_permissions(
&self,
permissions: Option<Vec<PermissionType>>,
request_updates_in_background: bool,
) -> crate::Result<PermissionStatus> {
self.0
.run_mobile_plugin(
"requestPermissions",
serde_json::json!({ "permissions": permissions }),
serde_json::json!({
"permissions": permissions,
"requestUpdatesInBackground": request_updates_in_background,
}),
)
.map_err(Into::into)
}
Expand Down