react-native/Libraries/Geolocation/RCTLocationObserver.m

336 lines
9.9 KiB
Mathematica
Raw Normal View History

/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
2015-03-09 10:04:44 +00:00
#import "RCTLocationObserver.h"
#import <CoreLocation/CLError.h>
#import <CoreLocation/CLLocationManager.h>
#import <CoreLocation/CLLocationManagerDelegate.h>
#import "RCTAssert.h"
#import "RCTBridge.h"
#import "RCTConvert.h"
#import "RCTEventDispatcher.h"
#import "RCTLog.h"
typedef NS_ENUM(NSInteger, RCTPositionErrorCode) {
RCTPositionErrorDenied = 1,
RCTPositionErrorUnavailable,
RCTPositionErrorTimeout,
};
#define RCT_DEFAULT_LOCATION_ACCURACY kCLLocationAccuracyHundredMeters
typedef struct {
double timeout;
double maximumAge;
double accuracy;
2015-03-09 10:04:44 +00:00
} RCTLocationOptions;
@implementation RCTConvert (RCTLocationOptions)
+ (RCTLocationOptions)RCTLocationOptions:(id)json
2015-03-09 10:04:44 +00:00
{
NSDictionary<NSString *, id> *options = [RCTConvert NSDictionary:json];
2015-03-09 10:04:44 +00:00
return (RCTLocationOptions){
.timeout = [RCTConvert NSTimeInterval:options[@"timeout"]] ?: INFINITY,
.maximumAge = [RCTConvert NSTimeInterval:options[@"maximumAge"]] ?: INFINITY,
.accuracy = [RCTConvert BOOL:options[@"enableHighAccuracy"]] ? kCLLocationAccuracyBest : RCT_DEFAULT_LOCATION_ACCURACY
};
}
@end
static NSDictionary<NSString *, id> *RCTPositionError(RCTPositionErrorCode code, NSString *msg /* nil for default */)
2015-03-09 10:04:44 +00:00
{
if (!msg) {
switch (code) {
case RCTPositionErrorDenied:
msg = @"User denied access to location services.";
break;
case RCTPositionErrorUnavailable:
msg = @"Unable to retrieve location.";
break;
case RCTPositionErrorTimeout:
msg = @"The location request timed out.";
break;
}
}
return @{
@"code": @(code),
@"message": msg,
@"PERMISSION_DENIED": @(RCTPositionErrorDenied),
@"POSITION_UNAVAILABLE": @(RCTPositionErrorUnavailable),
@"TIMEOUT": @(RCTPositionErrorTimeout)
};
}
@interface RCTLocationRequest : NSObject
@property (nonatomic, copy) RCTResponseSenderBlock successBlock;
@property (nonatomic, copy) RCTResponseSenderBlock errorBlock;
@property (nonatomic, assign) RCTLocationOptions options;
@property (nonatomic, strong) NSTimer *timeoutTimer;
@end
@implementation RCTLocationRequest
- (void)dealloc
{
if (_timeoutTimer.valid) {
[_timeoutTimer invalidate];
}
2015-03-09 10:04:44 +00:00
}
@end
@interface RCTLocationObserver () <CLLocationManagerDelegate>
@end
@implementation RCTLocationObserver
{
CLLocationManager *_locationManager;
NSDictionary<NSString *, id> *_lastLocationEvent;
NSMutableArray<RCTLocationRequest *> *_pendingRequests;
2015-03-09 10:04:44 +00:00
BOOL _observingLocation;
RCTLocationOptions _observerOptions;
}
RCT_EXPORT_MODULE()
2015-03-09 10:04:44 +00:00
@synthesize bridge = _bridge;
#pragma mark - Lifecycle
- (void)dealloc
{
[_locationManager stopUpdatingLocation];
_locationManager.delegate = nil;
2015-03-09 10:04:44 +00:00
}
- (dispatch_queue_t)methodQueue
{
return dispatch_get_main_queue();
}
2015-03-09 10:04:44 +00:00
#pragma mark - Private API
- (void)beginLocationUpdates
{
Refactored module access to allow for lazy loading Summary: public The `bridge.modules` dictionary provides access to all native modules, but this API requires that every module is initialized in advance so that any module can be accessed. This diff introduces a better API that will allow modules to be initialized lazily as they are needed, and deprecates `bridge.modules` (modules that use it will still work, but should be rewritten to use `bridge.moduleClasses` or `-[bridge moduleForName/Class:` instead. The rules are now as follows: * Any module that overrides `init` or `setBridge:` will be initialized on the main thread when the bridge is created * Any module that implements `constantsToExport:` will be initialized later when the config is exported (the module itself will be initialized on a background queue, but `constantsToExport:` will still be called on the main thread. * All other modules will be initialized lazily when a method is first called on them. These rules may seem slightly arcane, but they have the advantage of not violating any assumptions that may have been made by existing code - any module written under the original assumption that it would be initialized synchronously on the main thread when the bridge is created should still function exactly the same, but modules that avoid overriding `init` or `setBridge:` will now be loaded lazily. I've rewritten most of the standard modules to take advantage of this new lazy loading, with the following results: Out of the 65 modules included in UIExplorer: * 16 are initialized on the main thread when the bridge is created * A further 8 are initialized when the config is exported to JS * The remaining 41 will be initialized lazily on-demand Reviewed By: jspahrsummers Differential Revision: D2677695 fb-gh-sync-id: 507ae7e9fd6b563e89292c7371767c978e928f33
2015-11-25 11:09:00 +00:00
if (!_locationManager) {
_locationManager = [CLLocationManager new];
_locationManager.distanceFilter = RCT_DEFAULT_LOCATION_ACCURACY;
_locationManager.delegate = self;
}
2015-03-09 10:04:44 +00:00
// Request location access permission
if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[_locationManager requestWhenInUseAuthorization];
}
// Start observing location
[_locationManager startUpdatingLocation];
}
#pragma mark - Timeout handler
- (void)timeout:(NSTimer *)timer
{
RCTLocationRequest *request = timer.userInfo;
NSString *message = [NSString stringWithFormat: @"Unable to fetch location within %zds.", (NSInteger)(timer.timeInterval * 1000.0)];
request.errorBlock(@[RCTPositionError(RCTPositionErrorTimeout, message)]);
[_pendingRequests removeObject:request];
// Stop updating if no pending requests
if (_pendingRequests.count == 0 && !_observingLocation) {
[_locationManager stopUpdatingLocation];
}
}
#pragma mark - Public API
RCT_EXPORT_METHOD(startObserving:(RCTLocationOptions)options)
2015-03-09 10:04:44 +00:00
{
[self checkLocationConfig];
// Select best options
_observerOptions = options;
for (RCTLocationRequest *request in _pendingRequests) {
_observerOptions.accuracy = MIN(_observerOptions.accuracy, request.options.accuracy);
}
2015-03-09 10:04:44 +00:00
_locationManager.desiredAccuracy = _observerOptions.accuracy;
[self beginLocationUpdates];
_observingLocation = YES;
2015-03-09 10:04:44 +00:00
}
2015-04-08 15:52:48 +00:00
RCT_EXPORT_METHOD(stopObserving)
2015-03-09 10:04:44 +00:00
{
// Stop observing
_observingLocation = NO;
2015-03-09 10:04:44 +00:00
// Stop updating if no pending requests
if (_pendingRequests.count == 0) {
[_locationManager stopUpdatingLocation];
}
2015-03-09 10:04:44 +00:00
}
RCT_EXPORT_METHOD(getCurrentPosition:(RCTLocationOptions)options
2015-04-08 15:52:48 +00:00
withSuccessCallback:(RCTResponseSenderBlock)successBlock
errorCallback:(RCTResponseSenderBlock)errorBlock)
2015-03-09 10:04:44 +00:00
{
[self checkLocationConfig];
2015-03-09 10:04:44 +00:00
if (!successBlock) {
RCTLogError(@"%@.getCurrentPosition called with nil success parameter.", [self class]);
return;
}
if (![CLLocationManager locationServicesEnabled]) {
if (errorBlock) {
errorBlock(@[
RCTPositionError(RCTPositionErrorUnavailable, @"Location services disabled.")
]);
return;
2015-03-09 10:04:44 +00:00
}
}
2015-03-09 10:04:44 +00:00
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
if (errorBlock) {
errorBlock(@[
RCTPositionError(RCTPositionErrorDenied, nil)
]);
return;
2015-03-09 10:04:44 +00:00
}
}
2015-03-09 10:04:44 +00:00
// Check if previous recorded location exists and is good enough
if (_lastLocationEvent &&
CFAbsoluteTimeGetCurrent() - [RCTConvert NSTimeInterval:_lastLocationEvent[@"timestamp"]] < options.maximumAge &&
[_lastLocationEvent[@"coords"][@"accuracy"] doubleValue] >= options.accuracy) {
2015-03-09 10:04:44 +00:00
// Call success block with most recent known location
successBlock(@[_lastLocationEvent]);
return;
}
2015-03-09 10:04:44 +00:00
// Create request
RCTLocationRequest *request = [RCTLocationRequest new];
request.successBlock = successBlock;
request.errorBlock = errorBlock ?: ^(NSArray *args){};
request.options = options;
request.timeoutTimer = [NSTimer scheduledTimerWithTimeInterval:options.timeout
target:self
selector:@selector(timeout:)
userInfo:request
repeats:NO];
if (!_pendingRequests) {
_pendingRequests = [NSMutableArray new];
}
[_pendingRequests addObject:request];
// Configure location manager and begin updating location
_locationManager.desiredAccuracy = MIN(_locationManager.desiredAccuracy, options.accuracy);
[self beginLocationUpdates];
2015-03-09 10:04:44 +00:00
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray<CLLocation *> *)locations
2015-03-09 10:04:44 +00:00
{
// Create event
CLLocation *location = locations.lastObject;
2015-03-09 10:04:44 +00:00
_lastLocationEvent = @{
@"coords": @{
@"latitude": @(location.coordinate.latitude),
@"longitude": @(location.coordinate.longitude),
@"altitude": @(location.altitude),
@"accuracy": @(location.horizontalAccuracy),
@"altitudeAccuracy": @(location.verticalAccuracy),
@"heading": @(location.course),
@"speed": @(location.speed),
},
@"timestamp": @(CFAbsoluteTimeGetCurrent() * 1000.0) // in ms
};
// Send event
if (_observingLocation) {
[_bridge.eventDispatcher sendDeviceEventWithName:@"geolocationDidChange"
body:_lastLocationEvent];
}
// Fire all queued callbacks
for (RCTLocationRequest *request in _pendingRequests) {
request.successBlock(@[_lastLocationEvent]);
[request.timeoutTimer invalidate];
2015-03-09 10:04:44 +00:00
}
[_pendingRequests removeAllObjects];
// Stop updating if not not observing
if (!_observingLocation) {
[_locationManager stopUpdatingLocation];
}
// Reset location accuracy if desiredAccuracy is changed.
// Otherwise update accuracy will force triggering didUpdateLocations, watchPosition would keeping receiving location updates, even there's no location changes.
if (ABS(_locationManager.desiredAccuracy - RCT_DEFAULT_LOCATION_ACCURACY) > 0.000001) {
_locationManager.desiredAccuracy = RCT_DEFAULT_LOCATION_ACCURACY;
}
2015-03-09 10:04:44 +00:00
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
// Check error type
NSDictionary<NSString *, id> *jsError = nil;
2015-03-09 10:04:44 +00:00
switch (error.code) {
case kCLErrorDenied:
jsError = RCTPositionError(RCTPositionErrorDenied, nil);
break;
case kCLErrorNetwork:
jsError = RCTPositionError(RCTPositionErrorUnavailable, @"Unable to retrieve location due to a network failure");
break;
case kCLErrorLocationUnknown:
default:
jsError = RCTPositionError(RCTPositionErrorUnavailable, nil);
break;
}
// Send event
if (_observingLocation) {
[_bridge.eventDispatcher sendDeviceEventWithName:@"geolocationError"
body:jsError];
}
// Fire all queued error callbacks
for (RCTLocationRequest *request in _pendingRequests) {
request.errorBlock(@[jsError]);
[request.timeoutTimer invalidate];
2015-03-09 10:04:44 +00:00
}
[_pendingRequests removeAllObjects];
// Reset location accuracy if desiredAccuracy is changed.
// Otherwise update accuracy will force triggering didUpdateLocations, watchPosition would keeping receiving location updates, even there's no location changes.
if (ABS(_locationManager.desiredAccuracy - RCT_DEFAULT_LOCATION_ACCURACY) > 0.000001) {
_locationManager.desiredAccuracy = RCT_DEFAULT_LOCATION_ACCURACY;
}
2015-03-09 10:04:44 +00:00
}
- (void)checkLocationConfig
{
if (![[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"]) {
RCTLogError(@"NSLocationWhenInUseUsageDescription key must be present in Info.plist to use geolocation.");
}
}
2015-03-09 10:04:44 +00:00
@end