RNPNotification.m 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // RNPNotification.m
  3. // ReactNativePermissions
  4. //
  5. // Created by Yonah Forst on 11/07/16.
  6. // Copyright © 2016 Yonah Forst. All rights reserved.
  7. //
  8. #import "RNPNotification.h"
  9. static NSString* RNPDidAskForNotification = @"RNPDidAskForNotification";
  10. @interface RNPNotification()
  11. @property (copy) void (^completionHandler)(NSString*);
  12. @end
  13. @implementation RNPNotification
  14. + (NSString *)getStatus
  15. {
  16. BOOL didAskForPermission = [[NSUserDefaults standardUserDefaults] boolForKey:RNPDidAskForNotification];
  17. BOOL isRegistered = [[UIApplication sharedApplication] isRegisteredForRemoteNotifications];
  18. BOOL isEnabled = [[[UIApplication sharedApplication] currentUserNotificationSettings] types] != UIUserNotificationTypeNone;
  19. if (isRegistered || isEnabled) {
  20. return isEnabled ? RNPStatusAuthorized : RNPStatusDenied;
  21. } else {
  22. return didAskForPermission ? RNPStatusDenied : RNPStatusUndetermined;
  23. }
  24. }
  25. - (void)request:(UIUserNotificationType)types completionHandler:(void (^)(NSString*))completionHandler
  26. {
  27. NSString *status = [self.class getStatus];
  28. if (status == RNPStatusUndetermined) {
  29. self.completionHandler = completionHandler;
  30. [[NSNotificationCenter defaultCenter] addObserver:self
  31. selector:@selector(applicationDidBecomeActive)
  32. name:UIApplicationDidBecomeActiveNotification
  33. object:nil];
  34. UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
  35. [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
  36. [[UIApplication sharedApplication] registerForRemoteNotifications];
  37. [[NSUserDefaults standardUserDefaults] setBool:YES forKey:RNPDidAskForNotification];
  38. [[NSUserDefaults standardUserDefaults] synchronize];
  39. } else {
  40. completionHandler(status);
  41. }
  42. }
  43. - (void)applicationDidBecomeActive
  44. {
  45. [[NSNotificationCenter defaultCenter] removeObserver:self
  46. name:UIApplicationDidBecomeActiveNotification
  47. object:nil];
  48. if (self.completionHandler) {
  49. //for some reason, checking permission right away returns denied. need to wait a tiny bit
  50. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  51. self.completionHandler([self.class getStatus]);
  52. self.completionHandler = nil;
  53. });
  54. }
  55. }
  56. @end