1// Copyright 2018-present 650 Industries. All rights reserved.
2
3#import <EXNotifications/EXPushTokenManager.h>
4#import <ExpoModulesCore/EXDefines.h>
5
6@interface EXPushTokenManager ()
7
8@property (nonatomic, strong) NSPointerArray *listeners;
9
10@end
11
12@implementation EXPushTokenManager
13
14EX_REGISTER_SINGLETON_MODULE(PushTokenManager);
15
16- (instancetype)init
17{
18  if (self = [super init]) {
19    _listeners = [NSPointerArray weakObjectsPointerArray];
20  }
21  return self;
22}
23
24# pragma mark - UIApplicationDelegate
25
26- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
27{
28  for (int i = 0; i < _listeners.count; i++) {
29    id pointer = [_listeners pointerAtIndex:i];
30    [pointer onDidRegisterWithDeviceToken:deviceToken];
31  }
32}
33
34- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
35{
36  for (int i = 0; i < _listeners.count; i++) {
37    id pointer = [_listeners pointerAtIndex:i];
38    [pointer onDidFailToRegisterWithError:error];
39  }
40}
41
42# pragma mark - Listeners
43
44- (void)addListener:(id<EXPushTokenListener>)listener
45{
46  [_listeners addPointer:(__bridge void * _Nullable)(listener)];
47}
48
49- (void)removeListener:(id<EXPushTokenListener>)listener
50{
51  for (int i = 0; i < _listeners.count; i++) {
52    id pointer = [_listeners pointerAtIndex:i];
53    if (pointer == (__bridge void * _Nullable)(listener) || !pointer) {
54      [_listeners removePointerAtIndex:i];
55      i--;
56    }
57  }
58  // compact doesn't work, that's why we need the `|| !pointer` above
59  // http://www.openradar.me/15396578
60  [_listeners compact];
61}
62
63@end
64