-
-
Notifications
You must be signed in to change notification settings - Fork 822
/
LocationPlugin.m
389 lines (356 loc) · 12.9 KB
/
LocationPlugin.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
#import "LocationPlugin.h"
#ifdef COCOAPODS
@import CoreLocation;
#else
#import <CoreLocation/CoreLocation.h>
#endif
@interface LocationPlugin () <FlutterStreamHandler, CLLocationManagerDelegate>
@property(strong, nonatomic) CLLocationManager *clLocationManager;
@property(copy, nonatomic) FlutterResult flutterResult;
@property(assign, nonatomic) BOOL locationWanted;
@property(assign, nonatomic) BOOL permissionWanted;
// Needed to prevent instant firing of the previous known location
@property(assign, nonatomic) int waitNextLocation;
@property(copy, nonatomic) FlutterEventSink flutterEventSink;
@property(assign, nonatomic) BOOL flutterListening;
@property(assign, nonatomic) BOOL hasInit;
@property(assign, nonatomic) BOOL applicationHasLocationBackgroundMode;
@end
@implementation LocationPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
FlutterMethodChannel *channel =
[FlutterMethodChannel methodChannelWithName:@"lyokone/location"
binaryMessenger:registrar.messenger];
FlutterEventChannel *stream =
[FlutterEventChannel eventChannelWithName:@"lyokone/locationstream"
binaryMessenger:registrar.messenger];
LocationPlugin *instance = [[LocationPlugin alloc] init];
[registrar addMethodCallDelegate:instance channel:channel];
[stream setStreamHandler:instance];
}
- (instancetype)init {
self = [super init];
if (self) {
self.locationWanted = NO;
self.permissionWanted = NO;
self.flutterListening = NO;
self.waitNextLocation = 2;
self.hasInit = NO;
}
return self;
}
- (void)initLocation {
if (!(self.hasInit)) {
self.hasInit = YES;
NSArray *backgroundModes =
[NSBundle.mainBundle objectForInfoDictionaryKey:@"UIBackgroundModes"];
self.applicationHasLocationBackgroundMode =
[backgroundModes containsObject:@"location"];
self.clLocationManager = [[CLLocationManager alloc] init];
self.clLocationManager.delegate = self;
self.clLocationManager.desiredAccuracy = kCLLocationAccuracyBest;
}
}
- (void)handleMethodCall:(FlutterMethodCall *)call
result:(FlutterResult)result {
[self initLocation];
if ([call.method isEqualToString:@"changeSettings"]) {
if ([CLLocationManager locationServicesEnabled]) {
CLLocationAccuracy reducedAccuracy = kCLLocationAccuracyHundredMeters;
if (@available(iOS 14, *)) {
reducedAccuracy = kCLLocationAccuracyReduced;
}
NSDictionary *dictionary = @{
@"0" : @(kCLLocationAccuracyKilometer),
@"1" : @(kCLLocationAccuracyHundredMeters),
@"2" : @(kCLLocationAccuracyNearestTenMeters),
@"3" : @(kCLLocationAccuracyBest),
@"4" : @(kCLLocationAccuracyBestForNavigation),
@"5" : @(reducedAccuracy)
};
self.clLocationManager.desiredAccuracy =
[dictionary[call.arguments[@"accuracy"]] doubleValue];
double distanceFilter = [call.arguments[@"distanceFilter"] doubleValue];
if (distanceFilter == 0) {
distanceFilter = kCLDistanceFilterNone;
}
self.clLocationManager.distanceFilter = distanceFilter;
result(@1);
}
} else if ([call.method isEqualToString:@"isBackgroundModeEnabled"]) {
if (self.applicationHasLocationBackgroundMode) {
if (@available(iOS 9.0, *)) {
result(self.clLocationManager.allowsBackgroundLocationUpdates ? @1
: @0);
}
result(@0);
}
} else if ([call.method isEqualToString:@"enableBackgroundMode"]) {
BOOL enable = [call.arguments[@"enable"] boolValue];
if (self.applicationHasLocationBackgroundMode) {
if (@available(iOS 9.0, *)) {
self.clLocationManager.allowsBackgroundLocationUpdates = enable;
}
if (@available(iOS 11.0, *)) {
self.clLocationManager.showsBackgroundLocationIndicator = enable;
}
result(enable ? @1 : @0);
} else {
result(@0);
}
} else if ([call.method isEqualToString:@"getLocation"]) {
if (![CLLocationManager locationServicesEnabled]) {
result([FlutterError
errorWithCode:@"SERVICE_STATUS_DISABLED"
message:@"Failed to get location. Location services disabled"
details:nil]);
return;
}
if ([CLLocationManager authorizationStatus] ==
kCLAuthorizationStatusDenied) {
// Location services are requested but user has denied
NSString *message =
@"The user explicitly denied the use of location services for this "
"app or location services are currently disabled in Settings.";
result([FlutterError errorWithCode:@"PERMISSION_DENIED"
message:message
details:nil]);
return;
}
self.flutterResult = result;
self.locationWanted = YES;
if ([self isPermissionGranted]) {
[self.clLocationManager startUpdatingLocation];
} else {
[self requestPermission];
if ([self isPermissionGranted]) {
[self.clLocationManager startUpdatingLocation];
}
}
} else if ([call.method isEqualToString:@"hasPermission"]) {
if ([self isPermissionGranted]) {
result([self isHighAccuracyPermitted] ? @1 : @3);
} else {
result(@0);
}
} else if ([call.method isEqualToString:@"requestPermission"]) {
if ([self isPermissionGranted]) {
result([self isHighAccuracyPermitted] ? @1 : @3);
} else if ([CLLocationManager authorizationStatus] ==
kCLAuthorizationStatusNotDetermined) {
self.flutterResult = result;
self.permissionWanted = YES;
[self requestPermission];
} else {
result(@2);
}
} else if ([call.method isEqualToString:@"serviceEnabled"]) {
if ([CLLocationManager locationServicesEnabled]) {
result(@1);
} else {
result(@0);
}
} else if ([call.method isEqualToString:@"requestService"]) {
if ([CLLocationManager locationServicesEnabled]) {
result(@1);
} else {
#if TARGET_OS_OSX
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:@"Location is Disabled"];
[alert setInformativeText:
@"To use location, go to your System Preferences > Security & "
@"Privacy > Privacy > Location Services."];
[alert addButtonWithTitle:@"Open"];
[alert addButtonWithTitle:@"Cancel"];
[alert beginSheetModalForWindow:NSApplication.sharedApplication.mainWindow
completionHandler:^(NSModalResponse returnCode) {
if (returnCode == NSAlertFirstButtonReturn) {
NSString *urlString =
@"x-apple.systempreferences:com.apple.preference."
@"security?Privacy_LocationServices";
[[NSWorkspace sharedWorkspace]
openURL:[NSURL URLWithString:urlString]];
}
}];
#else
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Location is Disabled"
message:@"To use location, go to your Settings App > "
@"Privacy > Location Services."
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:nil];
[alert show];
#endif
result(@0);
}
} else {
result(FlutterMethodNotImplemented);
}
}
- (void)requestPermission {
#if TARGET_OS_OSX
if ([[NSBundle mainBundle]
objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"] !=
nil) {
if (@available(macOS 10.15, *)) {
[self.clLocationManager requestAlwaysAuthorization];
}
}
#else
if ([[NSBundle mainBundle]
objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"] !=
nil) {
[self.clLocationManager requestWhenInUseAuthorization];
} else if ([[NSBundle mainBundle] objectForInfoDictionaryKey:
@"NSLocationAlwaysUsageDescription"] !=
nil) {
[self.clLocationManager requestAlwaysAuthorization];
}
#endif
else {
[NSException
raise:NSInternalInconsistencyException
format:@"To use location in iOS8 and above you need to define either "
"NSLocationWhenInUseUsageDescription or "
"NSLocationAlwaysUsageDescription in the app "
"bundle's Info.plist file"];
}
}
- (BOOL)isHighAccuracyPermitted {
#if __IPHONE_14_0
if (@available(iOS 14.0, *)) {
CLAccuracyAuthorization accuracy =
[self.clLocationManager accuracyAuthorization];
if (accuracy == CLAccuracyAuthorizationReducedAccuracy) {
return NO;
}
}
#endif
return YES;
}
- (BOOL)isPermissionGranted {
BOOL isPermissionGranted = NO;
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
#if TARGET_OS_OSX
if (status == kCLAuthorizationStatusAuthorized) {
// Location services are available
isPermissionGranted = YES;
} else if (@available(macOS 10.12, *)) {
if (status == kCLAuthorizationStatusAuthorizedAlways) {
// Location services are available
isPermissionGranted = YES;
}
}
#else // if TARGET_OS_IOS
if (status == kCLAuthorizationStatusAuthorizedWhenInUse ||
status == kCLAuthorizationStatusAuthorizedAlways) {
// Location services are available
isPermissionGranted = YES;
}
#endif
else if (status == kCLAuthorizationStatusDenied ||
status == kCLAuthorizationStatusRestricted) {
// Location services are requested but user has denied / the app is
// restricted from getting location
isPermissionGranted = NO;
} else if (status == kCLAuthorizationStatusNotDetermined) {
// Location services never requested / the user still haven't decide
isPermissionGranted = NO;
} else {
isPermissionGranted = NO;
}
return isPermissionGranted;
}
- (FlutterError *)onListenWithArguments:(id)arguments
eventSink:(FlutterEventSink)events {
self.flutterEventSink = events;
self.flutterListening = YES;
if ([self isPermissionGranted]) {
[self.clLocationManager startUpdatingLocation];
} else {
[self requestPermission];
}
return nil;
}
- (FlutterError *)onCancelWithArguments:(id)arguments {
self.flutterListening = NO;
[self.clLocationManager stopUpdatingLocation];
return nil;
}
#pragma mark - CLLocationManagerDelegate Methods
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray<CLLocation *> *)locations {
if (self.waitNextLocation > 0) {
self.waitNextLocation -= 1;
return;
}
CLLocation *location = locations.lastObject;
NSTimeInterval timeInSeconds = [location.timestamp timeIntervalSince1970];
BOOL superiorToIos10 =
[UIDevice currentDevice].systemVersion.floatValue >= 10;
NSDictionary<NSString *, NSNumber *> *coordinatesDict = @{
@"latitude" : @(location.coordinate.latitude),
@"longitude" : @(location.coordinate.longitude),
@"accuracy" : @(location.horizontalAccuracy),
@"verticalAccuracy" : @(location.verticalAccuracy),
@"altitude" : @(location.altitude),
@"speed" : @(location.speed),
@"speed_accuracy" : superiorToIos10 ? @(location.speedAccuracy) : @0.0,
@"heading" : @(location.course),
@"time" :
@(((double)timeInSeconds) * 1000.0) // in milliseconds since the epoch
};
if (self.locationWanted) {
self.locationWanted = NO;
self.flutterResult(coordinatesDict);
}
if (self.flutterListening) {
self.flutterEventSink(coordinatesDict);
} else {
[self.clLocationManager stopUpdatingLocation];
self.waitNextLocation = 2;
}
}
- (void)locationManager:(CLLocationManager *)manager
didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
if (status == kCLAuthorizationStatusDenied) {
if (self.permissionWanted) {
self.permissionWanted = NO;
self.flutterResult(@0);
}
}
#if TARGET_OS_OSX
else if (status == kCLAuthorizationStatusAuthorized) {
if (self.permissionWanted) {
self.permissionWanted = NO;
self.flutterResult(@1);
}
if (self.locationWanted || self.flutterListening) {
[self.clLocationManager startUpdatingLocation];
}
} else if (@available(macOS 10.12, *)) {
if (status == kCLAuthorizationStatusAuthorizedAlways) {
if (self.permissionWanted) {
self.permissionWanted = NO;
self.flutterResult(@1);
}
if (self.locationWanted || self.flutterListening) {
[self.clLocationManager startUpdatingLocation];
}
}
}
#else // if TARGET_OS_IOS
else if (status == kCLAuthorizationStatusAuthorizedWhenInUse ||
status == kCLAuthorizationStatusAuthorizedAlways) {
if (self.permissionWanted) {
self.permissionWanted = NO;
self.flutterResult([self isHighAccuracyPermitted] ? @1 : @3);
}
if (self.locationWanted || self.flutterListening) {
[self.clLocationManager startUpdatingLocation];
}
}
#endif
}
@end