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