123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 *)getStatus
  16. {
  17. int status = [CLLocationManager authorizationStatus];
  18. switch (status) {
  19. case kCLAuthorizationStatusAuthorizedAlways:
  20. case kCLAuthorizationStatusAuthorizedWhenInUse:
  21. return RNPStatusAuthorized;
  22. case kCLAuthorizationStatusDenied:
  23. return RNPStatusDenied;
  24. case kCLAuthorizationStatusRestricted:
  25. return RNPStatusRestricted;
  26. default:
  27. return RNPStatusUndetermined;
  28. }
  29. }
  30. - (void)request:(NSString*)type completionHandler:(void (^)(NSString *))completionHandler
  31. {
  32. NSString *status = [RNPLocation getStatus];
  33. if (status == RNPStatusUndetermined) {
  34. self.completionHandler = completionHandler;
  35. if (self.locationManager == nil) {
  36. self.locationManager = [[CLLocationManager alloc] init];
  37. self.locationManager.delegate = self;
  38. }
  39. if ([type isEqualToString:@"always"]) {
  40. [self.locationManager requestAlwaysAuthorization];
  41. } else {
  42. [self.locationManager requestWhenInUseAuthorization];
  43. }
  44. } else {
  45. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse && [type isEqualToString:@"always"]) {
  46. completionHandler(RNPStatusDenied);
  47. } else {
  48. completionHandler(status);
  49. }
  50. }
  51. }
  52. -(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
  53. if (status != kCLAuthorizationStatusNotDetermined) {
  54. if (self.locationManager) {
  55. self.locationManager.delegate = nil;
  56. self.locationManager = nil;
  57. }
  58. if (self.completionHandler) {
  59. //for some reason, checking permission right away returns denied. need to wait a tiny bit
  60. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  61. self.completionHandler([RNPLocation getStatus]);
  62. self.completionHandler = nil;
  63. });
  64. }
  65. }
  66. }
  67. @end