12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. //
  2. // RNPLocation.m
  3. // ReactNativePermissions
  4. //
  5. // Created by Yonah Forst on 11/07/16.
  6. // Copyright © 2016 Yonah Forst. All rights reserved.
  7. //
  8. #import "RNPLocation.h"
  9. #import <CoreLocation/CoreLocation.h>
  10. @interface RNPLocation() <CLLocationManagerDelegate>
  11. @property (strong, nonatomic) CLLocationManager* locationManager;
  12. @property (copy) void (^completionHandler)(NSString *);
  13. @end
  14. @implementation RNPLocation
  15. + (NSString *)getStatusForType:(NSString *)type
  16. {
  17. int status = [CLLocationManager authorizationStatus];
  18. switch (status) {
  19. case kCLAuthorizationStatusAuthorizedAlways:
  20. return RNPStatusAuthorized;
  21. case kCLAuthorizationStatusAuthorizedWhenInUse:
  22. return [type isEqualToString:@"always"] ? RNPStatusDenied : RNPStatusAuthorized;
  23. case kCLAuthorizationStatusDenied:
  24. return RNPStatusDenied;
  25. case kCLAuthorizationStatusRestricted:
  26. return RNPStatusRestricted;
  27. default:
  28. return RNPStatusUndetermined;
  29. }
  30. }
  31. - (void)request:(NSString*)type completionHandler:(void (^)(NSString *))completionHandler
  32. {
  33. NSString *status = [RNPLocation getStatusForType:nil];
  34. if (status == RNPStatusUndetermined) {
  35. self.completionHandler = completionHandler;
  36. if (self.locationManager == nil) {
  37. self.locationManager = [[CLLocationManager alloc] init];
  38. self.locationManager.delegate = self;
  39. }
  40. if ([type isEqualToString:@"always"]) {
  41. [self.locationManager requestAlwaysAuthorization];
  42. } else {
  43. [self.locationManager requestWhenInUseAuthorization];
  44. }
  45. } else {
  46. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse && [type isEqualToString:@"always"]) {
  47. completionHandler(RNPStatusDenied);
  48. } else {
  49. completionHandler(status);
  50. }
  51. }
  52. }
  53. -(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
  54. if (status != kCLAuthorizationStatusNotDetermined) {
  55. if (self.locationManager) {
  56. self.locationManager.delegate = nil;
  57. self.locationManager = nil;
  58. }
  59. if (self.completionHandler) {
  60. //for some reason, checking permission right away returns denied. need to wait a tiny bit
  61. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  62. self.completionHandler([RNPLocation getStatusForType:nil]);
  63. self.completionHandler = nil;
  64. });
  65. }
  66. }
  67. }
  68. @end