RNPLocation.m 2.3KB

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