RNPNotification.m 2.4KB

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 isEnabled = [[[UIApplication sharedApplication] currentUserNotificationSettings] types] != UIUserNotificationTypeNone;
  18. if (isEnabled) {
  19. return RNPStatusAuthorized;
  20. } else {
  21. return didAskForPermission ? RNPStatusDenied : RNPStatusUndetermined;
  22. }
  23. }
  24. - (void)request:(UIUserNotificationType)types completionHandler:(void (^)(NSString*))completionHandler
  25. {
  26. NSString *status = [self.class getStatus];
  27. if (status == RNPStatusUndetermined) {
  28. self.completionHandler = completionHandler;
  29. [[NSNotificationCenter defaultCenter] addObserver:self
  30. selector:@selector(applicationDidBecomeActive)
  31. name:UIApplicationDidBecomeActiveNotification
  32. object:nil];
  33. UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
  34. [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
  35. [[UIApplication sharedApplication] registerForRemoteNotifications];
  36. [[NSUserDefaults standardUserDefaults] setBool:YES forKey:RNPDidAskForNotification];
  37. [[NSUserDefaults standardUserDefaults] synchronize];
  38. } else {
  39. completionHandler(status);
  40. }
  41. }
  42. - (void)applicationDidBecomeActive
  43. {
  44. [[NSNotificationCenter defaultCenter] removeObserver:self
  45. name:UIApplicationDidBecomeActiveNotification
  46. object:nil];
  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