123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. self.locationManager = [[CLLocationManager alloc] init];
  36. self.locationManager.delegate = self;
  37. if ([type isEqualToString:@"always"]) {
  38. [self.locationManager requestAlwaysAuthorization];
  39. } else {
  40. [self.locationManager requestWhenInUseAuthorization];
  41. }
  42. } else {
  43. completionHandler(status);
  44. }
  45. }
  46. -(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
  47. if (self.locationManager) {
  48. self.locationManager.delegate = nil;
  49. self.locationManager = nil;
  50. }
  51. if (self.completionHandler) {
  52. //for some reason, checking permission right away returns denied. need to wait a tiny bit
  53. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  54. self.completionHandler([RNPLocation getStatus]);
  55. self.completionHandler = nil;
  56. });
  57. }
  58. }
  59. @end