1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. completionHandler(status);
  46. }
  47. }
  48. -(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
  49. if (status != kCLAuthorizationStatusNotDetermined) {
  50. if (self.locationManager) {
  51. self.locationManager.delegate = nil;
  52. self.locationManager = nil;
  53. }
  54. if (self.completionHandler) {
  55. //for some reason, checking permission right away returns denied. need to wait a tiny bit
  56. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  57. self.completionHandler([RNPLocation getStatus]);
  58. self.completionHandler = nil;
  59. });
  60. }
  61. }
  62. }
  63. @end