12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //
  2. // RNPBluetooth.m
  3. // ReactNativePermissions
  4. //
  5. // Created by Yonah Forst on 11/07/16.
  6. // Copyright © 2016 Yonah Forst. All rights reserved.
  7. //
  8. #import "RNPBluetooth.h"
  9. #import <CoreBluetooth/CoreBluetooth.h>
  10. @interface RNPBluetooth() <CBPeripheralDelegate>
  11. @property (strong, nonatomic) CBPeripheralManager* peripheralManager;
  12. @property (copy) void (^completionHandler)(NSString *);
  13. @end
  14. @implementation RNPBluetooth
  15. + (NSString *)getStatus
  16. {
  17. int status = [CBPeripheralManager authorizationStatus];
  18. switch (status) {
  19. case CBPeripheralManagerAuthorizationStatusAuthorized:
  20. return RNPStatusAuthorized;
  21. case CBPeripheralManagerAuthorizationStatusDenied:
  22. return RNPStatusDenied;
  23. case CBPeripheralManagerAuthorizationStatusRestricted:
  24. return RNPStatusRestricted;
  25. default:
  26. return RNPStatusUndetermined;
  27. }
  28. }
  29. - (void)request:(void (^)(NSString *))completionHandler
  30. {
  31. NSString *status = [RNPBluetooth getStatus];
  32. if (status == RNPStatusUndetermined) {
  33. self.completionHandler = completionHandler;
  34. self.peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
  35. [self.peripheralManager startAdvertising:@{}];
  36. } else {
  37. completionHandler(status);
  38. }
  39. }
  40. - (void) peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheralManager
  41. {
  42. if (self.peripheralManager) {
  43. [self.peripheralManager stopAdvertising];
  44. self.peripheralManager.delegate = nil;
  45. self.peripheralManager = nil;
  46. }
  47. if (self.completionHandler) {
  48. //for some reason, checking permission right away returns denied. need to wait a tiny bit
  49. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  50. self.completionHandler([self.class getStatus]);
  51. self.completionHandler = nil;
  52. });
  53. }
  54. }
  55. @end