-
Notifications
You must be signed in to change notification settings - Fork 262
/
OneSignal.m
executable file
·2881 lines (2230 loc) · 122 KB
/
OneSignal.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Modified MIT License
*
* Copyright 2017 OneSignal
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* 1. The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 2. All copies of substantial portions of the Software may only be used in connection
* with services provided by OneSignal.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#import "OneSignal.h"
#import "OneSignalInternal.h"
#import "OneSignalTracker.h"
#import "OneSignalTrackIAP.h"
#import "OneSignalLocation.h"
#import "OneSignalReachability.h"
#import "OneSignalJailbreakDetection.h"
#import "OneSignalMobileProvision.h"
#import "OneSignalHelper.h"
#import "UNUserNotificationCenter+OneSignal.h"
#import "OneSignalSelectorHelpers.h"
#import "UIApplicationDelegate+OneSignal.h"
#import "NSString+OneSignal.h"
#import "OneSignalTrackFirebaseAnalytics.h"
#import "OneSignalNotificationServiceExtensionHandler.h"
#import "OSNotificationPayload+Internal.h"
#import "OSOutcomeEventsFactory.h"
#import "OSOutcomeEventsCache.h"
#import "OneSignalCommonDefines.h"
#import "OneSignalUserDefaults.h"
#import "OneSignalCacheCleaner.h"
#import "OSMigrationController.h"
#import "OneSignalNotificationSettings.h"
#import "OneSignalNotificationSettingsIOS10.h"
#import "OneSignalNotificationSettingsIOS8.h"
#import "OneSignalNotificationSettingsIOS7.h"
#import "OSObservable.h"
#import "OneSignalExtensionBadgeHandler.h"
#import <stdlib.h>
#import <stdio.h>
#import <sys/types.h>
#import <sys/utsname.h>
#import <sys/sysctl.h>
#import <objc/runtime.h>
#import <UIKit/UIKit.h>
#import "Requests.h"
#import "OneSignalClient.h"
#import <UserNotifications/UserNotifications.h>
#import "OneSignalSetEmailParameters.h"
#import "DelayedInitializationParameters.h"
#import "OneSignalDialogController.h"
#import "OSInfluenceDataDefines.h"
#import "OSInfluenceDataRepository.h"
#import "OSTrackerFactory.h"
#import "OSMessagingController.h"
#import "OSInAppMessageAction.h"
#import "OSInAppMessage.h"
#import "OneSignalLifecycleObserver.h"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
static ONE_S_LOG_LEVEL _nsLogLevel = ONE_S_LL_WARN;
static ONE_S_LOG_LEVEL _visualLogLevel = ONE_S_LL_NONE;
NSString* const kOSSettingsKeyAutoPrompt = @"kOSSettingsKeyAutoPrompt";
/* Enable the default in-app alerts*/
NSString* const kOSSettingsKeyInAppAlerts = @"kOSSettingsKeyInAppAlerts";
/* Enable the default in-app launch urls*/
NSString* const kOSSettingsKeyInAppLaunchURL = @"kOSSettingsKeyInAppLaunchURL";
/* Set InFocusDisplayOption value must be an OSNotificationDisplayType enum*/
NSString* const kOSSettingsKeyInFocusDisplayOption = @"kOSSettingsKeyInFocusDisplayOption";
/* Omit no app_id error logging, for use with wrapper SDKs. */
NSString* const kOSSettingsKeyInOmitNoAppIdLogging = @"kOSSettingsKeyInOmitNoAppIdLogging";
/* Determine whether to automatically open push notification URL's or prompt user for permission */
NSString* const kOSSSettingsKeyPromptBeforeOpeningPushURL = @"kOSSSettingsKeyPromptBeforeOpeningPushURL";
/* Used to determine if the app is able to present it's own customized Notification Settings view (iOS 12+) */
NSString* const kOSSettingsKeyProvidesAppNotificationSettings = @"kOSSettingsKeyProvidesAppNotificationSettings";
@implementation OSPermissionSubscriptionState
- (NSString*)description {
static NSString* format = @"<OSPermissionSubscriptionState:\npermissionStatus: %@,\nsubscriptionStatus: %@\n>";
return [NSString stringWithFormat:format, _permissionStatus, _subscriptionStatus];
}
- (NSDictionary*)toDictionary {
return @{@"permissionStatus": [_permissionStatus toDictionary],
@"subscriptionStatus": [_subscriptionStatus toDictionary],
@"emailSubscriptionStatus" : [_emailSubscriptionStatus toDictionary]
};
}
@end
@interface OSPendingCallbacks : NSObject
@property OSResultSuccessBlock successBlock;
@property OSFailureBlock failureBlock;
@end
@implementation OSPendingCallbacks
@end
@interface OneSignal (SessionStatusDelegate)
@end
@implementation OneSignal
NSString* const ONESIGNAL_VERSION = @"021502";
static NSString* mSDKType = @"native";
static BOOL coldStartFromTapOnNotification = NO;
static BOOL shouldDelaySubscriptionUpdate = false;
/*
if setEmail: was called before the device was registered (push playerID = nil),
then the call to setEmail: also gets delayed
this property stores the parameters so that once registration is complete
we can finish setEmail:
*/
static OneSignalSetEmailParameters *delayedEmailParameters;
static NSMutableArray* pendingSendTagCallbacks;
static OSResultSuccessBlock pendingGetTagsSuccessBlock;
static OSFailureBlock pendingGetTagsFailureBlock;
// Has attempted to register for push notifications with Apple since app was installed.
static BOOL registeredWithApple = NO;
// UIApplication-registerForRemoteNotifications has been called but a success or failure has not triggered yet.
static BOOL waitingForApnsResponse = false;
// Under Capabilities is "Background Modes" > "Remote notifications" enabled.
static BOOL backgroundModesEnabled = false;
static BOOL promptBeforeOpeningPushURLs = false;
// Indicates if initialization of the SDK has been delayed until the user gives privacy consent
static BOOL delayedInitializationForPrivacyConsent = false;
// If initialization is delayed, this object holds params such as the app ID so that the init()
// method can be called the moment the user provides privacy consent.
DelayedInitializationParameters *delayedInitParameters;
// Ensure we only initlize the SDK once even if the public method is called more.
static BOOL initDone;
//used to ensure registration occurs even if APNS does not respond
static NSDate *initializationTime;
static NSTimeInterval maxApnsWait = APNS_TIMEOUT;
static NSTimeInterval reattemptRegistrationInterval = REGISTRATION_DELAY_SECONDS;
// Set when the app is launched
static NSDate *sessionLaunchTime;
//the iOS Native SDK will use the plist flag to enable privacy consent
//however wrapper SDK's will use a method call before initialization
//this boolean flag is switched on to enable this behavior
static BOOL shouldRequireUserConsent = false;
static OneSignalTrackIAP* trackIAPPurchase;
static NSString* app_id;
NSString* emailToSet;
NSMutableDictionary* tagsToSend;
int mLastNotificationTypes = -1;
static int mSubscriptionStatus = -1;
OSIdsAvailableBlock idsAvailableBlockWhenReady;
BOOL disableBadgeClearing = NO;
BOOL mShareLocation = YES;
BOOL requestedProvisionalAuthorization = false;
BOOL usesAutoPrompt = false;
static BOOL providesAppNotificationSettings = false;
static BOOL performedOnSessionRequest = false;
static NSString *pendingExternalUserId;
static OSNotificationDisplayType _inFocusDisplayType = OSNotificationDisplayTypeInAppAlert;
+ (void)setInFocusDisplayType:(OSNotificationDisplayType)value {
NSInteger op = value;
if ([OneSignalHelper isIOSVersionLessThan:@"10.0"] && OSNotificationDisplayTypeNotification == op)
op = OSNotificationDisplayTypeInAppAlert;
_inFocusDisplayType = op;
}
+ (OSNotificationDisplayType)inFocusDisplayType {
return _inFocusDisplayType;
}
// iOS version implementation
static NSObject<OneSignalNotificationSettings>* _osNotificationSettings;
+ (NSObject<OneSignalNotificationSettings>*)osNotificationSettings {
if (!_osNotificationSettings) {
if ([OneSignalHelper isIOSVersionGreaterThanOrEqual:@"10.0"])
_osNotificationSettings = [OneSignalNotificationSettingsIOS10 new];
else if ([OneSignalHelper isIOSVersionGreaterThanOrEqual:@"8.0"])
_osNotificationSettings = [OneSignalNotificationSettingsIOS8 new];
else
_osNotificationSettings = [OneSignalNotificationSettingsIOS7 new];
}
return _osNotificationSettings;
}
// static property def for currentPermissionState
static OSPermissionState* _currentPermissionState;
+ (OSPermissionState*)currentPermissionState {
if (!_currentPermissionState) {
_currentPermissionState = [OSPermissionState alloc];
_currentPermissionState = [_currentPermissionState initAsTo];
[self lastPermissionState]; // Trigger creation
[_currentPermissionState.observable addObserver:[OSPermissionChangedInternalObserver alloc]];
}
return _currentPermissionState;
}
// static property def for previous OSSubscriptionState
static OSPermissionState* _lastPermissionState;
+ (OSPermissionState*)lastPermissionState {
if (!_lastPermissionState)
_lastPermissionState = [[OSPermissionState alloc] initAsFrom];
return _lastPermissionState;
}
+ (void)setLastPermissionState:(OSPermissionState *)lastPermissionState {
_lastPermissionState = lastPermissionState;
}
static OSEmailSubscriptionState* _currentEmailSubscriptionState;
+ (OSEmailSubscriptionState *)currentEmailSubscriptionState {
if (!_currentEmailSubscriptionState) {
_currentEmailSubscriptionState = [[OSEmailSubscriptionState alloc] init];
[_currentEmailSubscriptionState.observable addObserver:[OSEmailSubscriptionChangedInternalObserver alloc]];
}
return _currentEmailSubscriptionState;
}
static OSEmailSubscriptionState *_lastEmailSubscriptionState;
+ (OSEmailSubscriptionState *)lastEmailSubscriptionState {
if (!_lastEmailSubscriptionState) {
_lastEmailSubscriptionState = [[OSEmailSubscriptionState alloc] init];
}
return _lastEmailSubscriptionState;
}
+ (void)setLastEmailSubscriptionState:(OSEmailSubscriptionState *)lastEmailSubscriptionState {
_lastEmailSubscriptionState = lastEmailSubscriptionState;
}
// static property def for current OSSubscriptionState
static OSSubscriptionState* _currentSubscriptionState;
+ (OSSubscriptionState*)currentSubscriptionState {
if (!_currentSubscriptionState) {
_currentSubscriptionState = [OSSubscriptionState alloc];
_currentSubscriptionState = [_currentSubscriptionState initAsToWithPermision:self.currentPermissionState.accepted];
mLastNotificationTypes = _currentPermissionState.notificationTypes;
[self.currentPermissionState.observable addObserver:_currentSubscriptionState];
[_currentSubscriptionState.observable addObserver:[OSSubscriptionChangedInternalObserver alloc]];
}
return _currentSubscriptionState;
}
static OSSubscriptionState* _lastSubscriptionState;
+ (OSSubscriptionState*)lastSubscriptionState {
if (!_lastSubscriptionState) {
_lastSubscriptionState = [OSSubscriptionState alloc];
_lastSubscriptionState = [_lastSubscriptionState initAsFrom];
}
return _lastSubscriptionState;
}
+ (void)setLastSubscriptionState:(OSSubscriptionState*)lastSubscriptionState {
_lastSubscriptionState = lastSubscriptionState;
}
// static property def to add developer's OSPermissionStateChanges observers to.
static ObserablePermissionStateChangesType* _permissionStateChangesObserver;
+ (ObserablePermissionStateChangesType*)permissionStateChangesObserver {
if (!_permissionStateChangesObserver)
_permissionStateChangesObserver = [[OSObservable alloc] initWithChangeSelector:@selector(onOSPermissionChanged:)];
return _permissionStateChangesObserver;
}
static ObservableSubscriptionStateChangesType* _subscriptionStateChangesObserver;
+ (ObservableSubscriptionStateChangesType*)subscriptionStateChangesObserver {
if (!_subscriptionStateChangesObserver)
_subscriptionStateChangesObserver = [[OSObservable alloc] initWithChangeSelector:@selector(onOSSubscriptionChanged:)];
return _subscriptionStateChangesObserver;
}
static ObservableEmailSubscriptionStateChangesType* _emailSubscriptionStateChangesObserver;
+ (ObservableEmailSubscriptionStateChangesType *)emailSubscriptionStateChangesObserver {
if (!_emailSubscriptionStateChangesObserver)
_emailSubscriptionStateChangesObserver = [[OSObservable alloc] initWithChangeSelector:@selector(onOSEmailSubscriptionChanged:)];
return _emailSubscriptionStateChangesObserver;
}
+ (void)setMSubscriptionStatus:(NSNumber*)status {
mSubscriptionStatus = [status intValue];
}
static OSDevice* _userDevice;
+ (OSDevice *)getUserDevice {
if (!_userDevice)
_userDevice = [OSDevice new];
return _userDevice;
}
/*
Indicates if the iOS params request has started
Set to true when the method is called and set false if the request's failure callback is triggered
*/
static BOOL _didCallDownloadParameters = false;
+ (BOOL)didCallDownloadParameters {
return _didCallDownloadParameters;
}
/*
Indicates if the iOS params request is complete
Set to true when the request's success callback is triggered
*/
static BOOL _downloadedParameters = false;
+ (BOOL)downloadedParameters {
return _downloadedParameters;
}
static OneSignalReceiveReceiptsController* _receiveReceiptsController;
+ (OneSignalReceiveReceiptsController*)receiveReceiptsController {
if (!_receiveReceiptsController)
_receiveReceiptsController = [OneSignalReceiveReceiptsController new];
return _receiveReceiptsController;
}
static AppEntryAction _appEntryState = APP_CLOSE;
+ (AppEntryAction)appEntryState {
return _appEntryState;
}
+ (void)setAppEntryState:(AppEntryAction)appEntryState {
_appEntryState = appEntryState;
}
static OSInfluenceDataRepository *_influenceDataRepository;
+ (OSInfluenceDataRepository *)influenceDataRepository {
if (!_influenceDataRepository)
_influenceDataRepository = [OSInfluenceDataRepository new];
return _influenceDataRepository;
}
static OSTrackerFactory *_trackerFactory;
+ (OSTrackerFactory*)trackerFactory {
if (!_trackerFactory)
_trackerFactory = [[OSTrackerFactory alloc] initWithRepository:OneSignal.influenceDataRepository];
return _trackerFactory;
}
static OSSessionManager *_sessionManager;
+ (OSSessionManager*)sessionManager {
if (!_sessionManager)
_sessionManager = [[OSSessionManager alloc] init:self withTrackerFactory:OneSignal.trackerFactory];
return _sessionManager;
}
static OSOutcomeEventsCache *_outcomeEventsCache;
+ (OSOutcomeEventsCache *)outcomeEventsCache {
if (!_outcomeEventsCache)
_outcomeEventsCache = [[OSOutcomeEventsCache alloc] init];
return _outcomeEventsCache;
}
static OSOutcomeEventsFactory *_outcomeEventFactory;
+ (OSOutcomeEventsFactory *)outcomeEventFactory {
return _outcomeEventFactory;
}
static OneSignalOutcomeEventsController *_outcomeEventsController;
+ (OneSignalOutcomeEventsController *)getOutcomeEventsController {
return _outcomeEventsController;
}
+ (NSString*)app_id {
return app_id;
}
+ (NSString*)sdk_version_raw {
return ONESIGNAL_VERSION;
}
+ (NSString*)sdk_semantic_version {
// examples:
// ONESIGNAL_VERSION = @"020402" returns 2.4.2
// ONESIGNAL_VERSION = @"001000" returns 0.10.0
// so that's 6 digits, where the first two are the major version
// the second two are the minor version and that last two, the patch.
// c.f. http://semver.org/
return [ONESIGNAL_VERSION one_getSemanticVersion];
}
+ (NSString*)mUserId {
return self.currentSubscriptionState.userId;
}
+ (NSString *)mEmailAuthToken {
return self.currentEmailSubscriptionState.emailAuthCode;
}
+ (NSString *)mEmailUserId {
return self.currentEmailSubscriptionState.emailUserId;
}
+ (void)setMSDKType:(NSString*)type {
mSDKType = type;
}
+ (void) setWaitingForApnsResponse:(BOOL)value {
waitingForApnsResponse = value;
}
// Used for testing purposes to decrease the amount of time the
// SDK will spend waiting for a response from APNS before it
// gives up and registers with OneSignal anyways
+ (void)setDelayIntervals:(NSTimeInterval)apnsMaxWait withRegistrationDelay:(NSTimeInterval)registrationDelay {
reattemptRegistrationInterval = registrationDelay;
maxApnsWait = apnsMaxWait;
}
+ (void)clearStatics {
initDone = false;
usesAutoPrompt = false;
requestedProvisionalAuthorization = false;
app_id = nil;
registeredWithApple = false;
_osNotificationSettings = nil;
waitingForApnsResponse = false;
waitingForOneSReg = false;
isOnSessionSuccessfulForCurrentState = false;
mLastNotificationTypes = -1;
_lastPermissionState = nil;
_currentPermissionState = nil;
_currentEmailSubscriptionState = nil;
_lastEmailSubscriptionState = nil;
_lastSubscriptionState = nil;
_currentSubscriptionState = nil;
_permissionStateChangesObserver = nil;
_downloadedParameters = false;
_didCallDownloadParameters = false;
maxApnsWait = APNS_TIMEOUT;
reattemptRegistrationInterval = REGISTRATION_DELAY_SECONDS;
sessionLaunchTime = [NSDate date];
performedOnSessionRequest = false;
pendingExternalUserId = nil;
_trackerFactory = nil;
_sessionManager = nil;
_outcomeEventsCache = nil;
_outcomeEventFactory = nil;
_outcomeEventsController = nil;
}
// Set to false as soon as it's read.
+ (BOOL)coldStartFromTapOnNotification {
BOOL val = coldStartFromTapOnNotification;
coldStartFromTapOnNotification = NO;
return val;
}
+ (BOOL)shouldDelaySubscriptionSettingsUpdate {
return shouldDelaySubscriptionUpdate;
}
+ (id)initWithLaunchOptions:(NSDictionary*)launchOptions appId:(NSString*)appId {
return [self initWithLaunchOptions:launchOptions
appId:appId
handleNotificationReceived:NULL
handleNotificationAction:NULL
settings:@{
kOSSettingsKeyAutoPrompt :@YES,
kOSSettingsKeyInAppAlerts : @YES,
kOSSettingsKeyInAppLaunchURL : @YES,
kOSSSettingsKeyPromptBeforeOpeningPushURL : @NO
}];
}
+ (id)initWithLaunchOptions:(NSDictionary*)launchOptions
appId:(NSString*)appId
handleNotificationAction:(OSHandleNotificationActionBlock)actionCallback {
return [self initWithLaunchOptions:launchOptions
appId:appId
handleNotificationReceived:NULL
handleNotificationAction:actionCallback
settings:@{
kOSSettingsKeyAutoPrompt : @YES,
kOSSettingsKeyInAppAlerts : @YES,
kOSSettingsKeyInAppLaunchURL : @YES,
kOSSSettingsKeyPromptBeforeOpeningPushURL : @NO
}];
}
+ (id)initWithLaunchOptions:(NSDictionary*)launchOptions
appId:(NSString*)appId
handleNotificationAction:(OSHandleNotificationActionBlock)actionCallback
settings:(NSDictionary*)settings {
return [self initWithLaunchOptions:launchOptions
appId:appId
handleNotificationReceived:NULL
handleNotificationAction:actionCallback
settings:settings];
}
// NOTE: Wrapper SDKs such as Unity3D will call this method with appId set to nil so open events are not lost.
// Ensure a 2nd call can be made later with the appId from the developer's code.
+ (id)initWithLaunchOptions:(NSDictionary*)launchOptions
appId:(NSString*)appId
handleNotificationReceived:(OSHandleNotificationReceivedBlock)receivedCallback
handleNotificationAction:(OSHandleNotificationActionBlock)actionCallback
settings:(NSDictionary*)settings {
[self onesignal_Log:ONE_S_LL_VERBOSE message:[NSString stringWithFormat:@"Called init with app ID: %@", appId]];
[[OSMigrationController new] migrate];
[OneSignalHelper setNotificationActionBlock:actionCallback];
[OneSignalHelper setNotificationReceivedBlock:receivedCallback];
if ([self requiresUserPrivacyConsent]) {
delayedInitializationForPrivacyConsent = true;
delayedInitParameters = [[DelayedInitializationParameters alloc] initWithLaunchOptions:launchOptions
withAppId:appId
withHandleNotificationReceivedBlock:receivedCallback
withHandleNotificationActionBlock:actionCallback
withSettings:settings];
[self onesignal_Log:ONE_S_LL_VERBOSE message:@"Delayed initialization of the OneSignal SDK until the user provides privacy consent using the consentGranted() method"];
return self;
}
[OneSignalCacheCleaner cleanCachedUserData];
[OneSignal checkIfApplicationImplementsDeprecatedMethods];
let success = [self initAppId:appId withSettings:settings];
if (!success)
return self;
// Wrapper SDK's call init twice and pass null as the appId on the first call
// the app ID is required to download parameters, so do not download params until the appID is provided
if (!_didCallDownloadParameters && appId && appId != (id)[NSNull null])
[self downloadIOSParamsWithAppId:appId];
let standardUserDefaults = OneSignalUserDefaults.initStandard;
[self initSettings:settings withStandardUserDefaults:standardUserDefaults];
if (initDone)
return self;
initDone = true;
initializationTime = [NSDate date];
// Outcomes init
_outcomeEventFactory = [[OSOutcomeEventsFactory alloc] initWithCache:OneSignal.outcomeEventsCache];
_outcomeEventsController = [[OneSignalOutcomeEventsController alloc] initWithSessionManager:OneSignal.sessionManager outcomeEventsFactory:_outcomeEventFactory];
if (appId && mShareLocation)
[OneSignalLocation getLocation:false fallbackToSettings:false withCompletionHandler:nil];
/*
* No need to call the handleNotificationOpened:userInfo as it will be called from one of the following selectors
* - application:didReceiveRemoteNotification:fetchCompletionHandler
* - userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler (iOS10)
*/
// Cold start from tap on a remote notification
// NOTE: launchOptions may be nil if tapping on a notification's action button.
NSDictionary* userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (userInfo)
coldStartFromTapOnNotification = YES;
[self clearBadgeCount:false];
if (!trackIAPPurchase && [OneSignalTrackIAP canTrack])
trackIAPPurchase = [OneSignalTrackIAP new];
if ([OneSignalTrackFirebaseAnalytics libraryExists])
[OneSignalTrackFirebaseAnalytics init];
[OneSignalLifecycleObserver registerLifecycleObserver];
return self;
}
+ (NSString *)appGroupKey {
return [OneSignalExtensionBadgeHandler appGroupName];
}
+ (bool)initAppId:(NSString*)appId withSettings:(NSDictionary*)settings {
// TODO: Maybe in the future we can make a file with add app ids and validate that way?
if ([@"b2f7f966-d8cc-11e4-bed1-df8f05be55ba" isEqualToString:appId] ||
[@"5eb5a37e-b458-11e3-ac11-000c2940e62c" isEqualToString:appId]) {
onesignal_Log(ONE_S_LL_WARN, @"OneSignal Example AppID detected, please update to your app's id found on OneSignal.com");
}
let standardUserDefaults = OneSignalUserDefaults.initStandard;
let prevAppId = [standardUserDefaults getSavedStringForKey:OSUD_APP_ID defaultValue:nil];
if (appId) {
app_id = appId;
} else {
// Read from .plist if not passed in with this method call.
app_id = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"OneSignal_APPID"];
if (!app_id) {
app_id = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"GameThrive_APPID"];
if (!app_id)
app_id = prevAppId;
if (![settings[kOSSettingsKeyInOmitNoAppIdLogging] boolValue])
onesignal_Log(ONE_S_LL_FATAL, @"OneSignal AppId never set!");
else
return true;
}
}
// Handle changes to the app id, this might happen on a developer's device when testing
// Will also run the first time OneSignal is initialized
if (app_id && ![app_id isEqualToString:prevAppId]) {
initDone = false;
_downloadedParameters = false;
_didCallDownloadParameters = false;
let sharedUserDefaults = OneSignalUserDefaults.initShared;
[standardUserDefaults saveStringForKey:OSUD_APP_ID withValue:app_id];
// Remove player_id from both standard and shared NSUserDefaults
[standardUserDefaults removeValueForKey:OSUD_PLAYER_ID_TO];
[sharedUserDefaults removeValueForKey:OSUD_PLAYER_ID_TO];
}
// Always save app_id and player_id as it will not be present on shared if:
// - Updating from an older SDK
// - Updating to an app that didn't have App Groups setup before
[OneSignalUserDefaults.initShared saveStringForKey:OSUD_APP_ID withValue:app_id];
[OneSignalUserDefaults.initShared saveStringForKey:OSUD_PLAYER_ID_TO withValue:self.currentSubscriptionState.userId];
// Invalid app ids reaching here will cause failure
if (!app_id || ![[NSUUID alloc] initWithUUIDString:app_id]) {
onesignal_Log(ONE_S_LL_FATAL, @"OneSignal AppId format is invalid.\nExample: 'b2f7f966-d8cc-11e4-bed1-df8f05be55ba'\n");
return false;
}
return true;
}
+ (void)initSettings:(NSDictionary*)settings withStandardUserDefaults:(OneSignalUserDefaults*)standardUserDefaults {
if ([OneSignalHelper isIOSVersionGreaterThanOrEqual:@"8.0"])
registeredWithApple = self.currentPermissionState.accepted;
else
registeredWithApple = self.currentSubscriptionState.pushToken || [standardUserDefaults getSavedBoolForKey:OSUD_REGISTERED_WITH_APPLE defaultValue:false];
// Check if disabled in-app launch url if passed a NO
if (settings[kOSSettingsKeyInAppLaunchURL] && [settings[kOSSettingsKeyInAppLaunchURL] isKindOfClass:[NSNumber class]])
[self enableInAppLaunchURL:[settings[kOSSettingsKeyInAppLaunchURL] boolValue]];
else if (![standardUserDefaults keyExists:OSUD_NOTIFICATION_OPEN_LAUNCH_URL]) {
// Only need to default to true if the app doesn't already have this setting saved in NSUserDefaults
[self enableInAppLaunchURL:true];
}
if (settings[kOSSSettingsKeyPromptBeforeOpeningPushURL] && [settings[kOSSSettingsKeyPromptBeforeOpeningPushURL] isKindOfClass:[NSNumber class]]) {
promptBeforeOpeningPushURLs = [settings[kOSSSettingsKeyPromptBeforeOpeningPushURL] boolValue];
[standardUserDefaults saveBoolForKey:OSUD_PROMPT_BEFORE_NOTIFICATION_LAUNCH_URL_OPENS withValue:promptBeforeOpeningPushURLs];
}
else
promptBeforeOpeningPushURLs = [standardUserDefaults getSavedBoolForKey:OSUD_PROMPT_BEFORE_NOTIFICATION_LAUNCH_URL_OPENS defaultValue:false];
usesAutoPrompt = YES;
if (settings[kOSSettingsKeyAutoPrompt] && [settings[kOSSettingsKeyAutoPrompt] isKindOfClass:[NSNumber class]])
usesAutoPrompt = [settings[kOSSettingsKeyAutoPrompt] boolValue];
if (settings[kOSSettingsKeyProvidesAppNotificationSettings] && [settings[kOSSettingsKeyProvidesAppNotificationSettings] isKindOfClass:[NSNumber class]] && [OneSignalHelper isIOSVersionGreaterThanOrEqual:@"12.0"])
providesAppNotificationSettings = [settings[kOSSettingsKeyProvidesAppNotificationSettings] boolValue];
// Register with Apple's APNS server if we registed once before or if auto-prompt hasn't been disabled.
if (usesAutoPrompt || registeredWithApple)
[self registerForPushNotifications];
else {
[self checkProvisionalAuthorizationStatus];
[self registerForAPNsToken];
}
/* Check if in-app setting passed assigned
* LOGIC: Default - InAppAlerts enabled / InFocusDisplayOption InAppAlert.
* Priority for kOSSettingsKeyInFocusDisplayOption.
*/
NSNumber *IAASetting = settings[kOSSettingsKeyInAppAlerts];
let inAppAlertsPassed = IAASetting && (IAASetting.integerValue == 0 || IAASetting.integerValue == 1);
NSNumber *IFDSetting = settings[kOSSettingsKeyInFocusDisplayOption];
let inFocusDisplayPassed = IFDSetting && IFDSetting.integerValue > -1 && IFDSetting.integerValue < 3;
if (inAppAlertsPassed || inFocusDisplayPassed) {
if (!inFocusDisplayPassed)
self.inFocusDisplayType = (OSNotificationDisplayType)IAASetting.integerValue;
else
self.inFocusDisplayType = (OSNotificationDisplayType)IFDSetting.integerValue;
}
if (self.currentSubscriptionState.userId)
[self registerUser];
else {
[self.osNotificationSettings getNotificationPermissionState:^(OSPermissionState *state) {
if (state.answeredPrompt)
[self registerUser];
else
[self registerUserAfterDelay];
}];
}
}
// Checks to see if we should register for APNS' new Provisional authorization
// (also known as Direct to History).
// This behavior is determined by the OneSignal Parameters request
+ (void)checkProvisionalAuthorizationStatus {
if ([self shouldLogMissingPrivacyConsentErrorWithMethodName:nil])
return;
BOOL usesProvisional = [OneSignalUserDefaults.initStandard getSavedBoolForKey:OSUD_USES_PROVISIONAL_PUSH_AUTHORIZATION defaultValue:false];
// if iOS parameters for this app have never downloaded, this method
// should return
if (!usesProvisional || requestedProvisionalAuthorization)
return;
requestedProvisionalAuthorization = true;
[self.osNotificationSettings registerForProvisionalAuthorization:nil];
}
+ (void)registerForProvisionalAuthorization:(void(^)(BOOL accepted))completionHandler {
if ([OneSignalHelper isIOSVersionGreaterThanOrEqual:@"12.0"])
[self.osNotificationSettings registerForProvisionalAuthorization:completionHandler];
else
onesignal_Log(ONE_S_LL_WARN, @"registerForProvisionalAuthorization is only available in iOS 12+.");
}
+ (BOOL)shouldLogMissingPrivacyConsentErrorWithMethodName:(NSString *)methodName {
if ([self requiresUserPrivacyConsent]) {
if (methodName) {
[self onesignal_Log:ONE_S_LL_WARN message:[NSString stringWithFormat:@"Your application has called %@ before the user granted privacy permission. Please call `consentGranted(bool)` in order to provide user privacy consent", methodName]];
}
return true;
}
return false;
}
+ (void)setRequiresUserPrivacyConsent:(BOOL)required {
shouldRequireUserConsent = required;
}
+ (BOOL)requiresUserPrivacyConsent {
// if the plist key does not exist default to true
// the plist value specifies whether GDPR privacy consent is required for this app
// if required and consent has not been previously granted, return false
let requiresConsent = [[[NSBundle mainBundle] objectForInfoDictionaryKey:ONESIGNAL_REQUIRE_PRIVACY_CONSENT] boolValue] ?: false;
if (requiresConsent || shouldRequireUserConsent)
return ![OneSignalUserDefaults.initStandard getSavedBoolForKey:GDPR_CONSENT_GRANTED defaultValue:false];
return false;
}
+ (void)consentGranted:(BOOL)granted {
[OneSignalUserDefaults.initStandard saveBoolForKey:GDPR_CONSENT_GRANTED withValue:granted];
if (!granted || !delayedInitializationForPrivacyConsent || delayedInitParameters == nil)
return;
[self initWithLaunchOptions:delayedInitParameters.launchOptions appId:delayedInitParameters.appId handleNotificationReceived:delayedInitParameters.receivedBlock handleNotificationAction:delayedInitParameters.actionBlock settings:delayedInitParameters.settings];
delayedInitializationForPrivacyConsent = false;
delayedInitParameters = nil;
}
// the iOS SDK used to call these selectors as a convenience but has stopped due to concerns about private API usage
// the SDK will now print warnings when a developer's app implements these selectors
+ (void)checkIfApplicationImplementsDeprecatedMethods {
dispatch_async(dispatch_get_main_queue(), ^{
for (NSString *selectorName in DEPRECATED_SELECTORS)
if ([[[UIApplication sharedApplication] delegate] respondsToSelector:NSSelectorFromString(selectorName)])
[OneSignal onesignal_Log:ONE_S_LL_WARN message:[NSString stringWithFormat:@"OneSignal has detected that your application delegate implements a deprecated method (%@). Please note that this method has been officially deprecated and the OneSignal SDK will no longer call it. You should use UNUserNotificationCenter instead", selectorName]];
});
}
+ (void)downloadIOSParamsWithAppId:(NSString *)appId {
[self onesignal_Log:ONE_S_LL_DEBUG message:@"Downloading iOS parameters for this application"];
_didCallDownloadParameters = true;
[OneSignalClient.sharedClient executeRequest:[OSRequestGetIosParams withUserId:self.currentSubscriptionState.userId appId:appId] onSuccess:^(NSDictionary *result) {
if (result[IOS_REQUIRES_EMAIL_AUTHENTICATION]) {
self.currentEmailSubscriptionState.requiresEmailAuth = [result[IOS_REQUIRES_EMAIL_AUTHENTICATION] boolValue];
// checks if a cell to setEmail: was delayed due to missing 'requiresEmailAuth' parameter
if (delayedEmailParameters && self.currentSubscriptionState.userId) {
[self setEmail:delayedEmailParameters.email withEmailAuthHashToken:delayedEmailParameters.authToken withSuccess:delayedEmailParameters.successBlock withFailure:delayedEmailParameters.failureBlock];
delayedEmailParameters = nil;
}
}
if (!usesAutoPrompt && result[IOS_USES_PROVISIONAL_AUTHORIZATION] != (id)[NSNull null]) {
[OneSignalUserDefaults.initStandard saveBoolForKey:OSUD_USES_PROVISIONAL_PUSH_AUTHORIZATION withValue:[result[IOS_USES_PROVISIONAL_AUTHORIZATION] boolValue]];
[self checkProvisionalAuthorizationStatus];
}
if (result[IOS_RECEIVE_RECEIPTS_ENABLE] != (id)[NSNull null])
[OneSignalUserDefaults.initShared saveBoolForKey:OSUD_RECEIVE_RECEIPTS_ENABLED withValue:[result[IOS_RECEIVE_RECEIPTS_ENABLE] boolValue]];
if (result[OUTCOMES_PARAM] && result[OUTCOMES_PARAM][IOS_OUTCOMES_V2_SERVICE_ENABLE])
[_outcomeEventsCache saveOutcomesV2ServiceEnabled:result[OUTCOMES_PARAM][IOS_OUTCOMES_V2_SERVICE_ENABLE]];
[OneSignal.trackerFactory saveInfluenceParams:result];
[OneSignalTrackFirebaseAnalytics updateFromDownloadParams:result];
_downloadedParameters = true;
} onFailure:^(NSError *error) {
_didCallDownloadParameters = false;
}];
}
+ (void)setLogLevel:(ONE_S_LOG_LEVEL)nsLogLevel visualLevel:(ONE_S_LOG_LEVEL)visualLogLevel {
_nsLogLevel = nsLogLevel; _visualLogLevel = visualLogLevel;
}
+ (void) onesignal_Log:(ONE_S_LOG_LEVEL)logLevel message:(NSString*) message {
onesignal_Log(logLevel, message);
}
void onesignal_Log(ONE_S_LOG_LEVEL logLevel, NSString* message) {
NSString* levelString;
switch (logLevel) {
case ONE_S_LL_FATAL:
levelString = @"FATAL: ";
break;
case ONE_S_LL_ERROR:
levelString = @"ERROR: ";
break;
case ONE_S_LL_WARN:
levelString = @"WARNING: ";
break;
case ONE_S_LL_INFO:
levelString = @"INFO: ";
break;
case ONE_S_LL_DEBUG:
levelString = @"DEBUG: ";
break;
case ONE_S_LL_VERBOSE:
levelString = @"VERBOSE: ";
break;
default:
break;
}
if (logLevel <= _nsLogLevel)
NSLog(@"%@", [levelString stringByAppendingString:message]);
if (logLevel <= _visualLogLevel) {
[[OneSignalDialogController sharedInstance] presentDialogWithTitle:levelString withMessage:message withActions:nil cancelTitle:NSLocalizedString(@"Close", @"Close button") withActionCompletion:nil];
}
}
//presents the settings page to control/customize push notification settings
+ (void)presentAppSettings {
//only supported in 10+
if ([OneSignalHelper isIOSVersionLessThan:@"10.0"])
return;
let url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
if (!url)
return;
if ([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
} else {
[self onesignal_Log:ONE_S_LL_ERROR message:@"Unable to open settings for this application"];
}
}
// iOS 12+ only
// A boolean indicating if the app provides its own custom Notifications Settings UI
// If this is set to TRUE via the kOSSettingsKeyProvidesAppNotificationSettings init
// parameter, the SDK will request authorization from the User Notification Center
+ (BOOL)providesAppNotificationSettings {
return providesAppNotificationSettings;
}
// iOS 8+, only tries to register for an APNs token
+ (BOOL)registerForAPNsToken {
if ([OneSignalHelper isIOSVersionLessThan:@"8.0"])
return false;
if (waitingForApnsResponse)
return true;
id backgroundModes = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIBackgroundModes"];
backgroundModesEnabled = (backgroundModes && [backgroundModes containsObject:@"remote-notification"]);
// Only try to register for a pushToken if:
// - The user accepted notifications
// - "Background Modes" > "Remote Notifications" are enabled in Xcode
if (![self.osNotificationSettings getNotificationPermissionState].accepted && !backgroundModesEnabled)
return false;
// Don't attempt to register again if there was a non-recoverable error.
if (mSubscriptionStatus < -9)
return false;
[OneSignal onesignal_Log:ONE_S_LL_VERBOSE message:@"Firing registerForRemoteNotifications"];
waitingForApnsResponse = true;
[OneSignalHelper dispatch_async_on_main_queue:^{
[[UIApplication sharedApplication] registerForRemoteNotifications];
}];
return true;
}
// if user has disabled push notifications & fallback == true,
// the SDK will prompt the user to open notification Settings for this app
+ (void)promptForPushNotificationsWithUserResponse:(void (^)(BOOL accepted))completionHandler fallbackToSettings:(BOOL)fallback {
if (self.currentPermissionState.hasPrompted == true && self.osNotificationSettings.getNotificationTypes == 0 && fallback) {
//show settings
if (completionHandler)
completionHandler(false);
let localizedTitle = NSLocalizedString(@"Open Settings", @"A title saying that the user can open iOS Settings");
let localizedSettingsActionTitle = NSLocalizedString(@"Open Settings", @"A button allowing the user to open the Settings app");
let localizedCancelActionTitle = NSLocalizedString(@"Cancel", @"A button allowing the user to close the Settings prompt");
//the developer can provide a custom message in Info.plist if they choose.
var localizedMessage = (NSString *)[[NSBundle mainBundle] objectForInfoDictionaryKey:FALLBACK_TO_SETTINGS_MESSAGE];
if (!localizedMessage)
localizedMessage = NSLocalizedString(@"You currently have notifications turned off for this application. You can open Settings to re-enable them", @"A message explaining that users can open Settings to re-enable push notifications");
[[OneSignalDialogController sharedInstance] presentDialogWithTitle:localizedTitle withMessage:localizedMessage withActions:@[localizedSettingsActionTitle] cancelTitle:localizedCancelActionTitle withActionCompletion:^(int tappedActionIndex) {
//completion is called on the main thread
if (tappedActionIndex > -1)
[self presentAppSettings];
}];
return;
}
[self promptForPushNotificationsWithUserResponse:completionHandler];