-
Notifications
You must be signed in to change notification settings - Fork 263
/
OneSignal.m
executable file
·814 lines (656 loc) · 33.8 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
/**
* 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 "OneSignalFramework.h"
#import "OneSignalInternal.h"
#import "OneSignalTracker.h"
#import "OneSignalTrackIAP.h"
#import "OneSignalJailbreakDetection.h"
#import "OneSignalMobileProvision.h"
#import "OneSignalHelper.h"
// #import "UNUserNotificationCenter+OneSignal.h" // TODO: This is in Notifications
#import "OneSignalSelectorHelpers.h"
#import "UIApplicationDelegate+OneSignal.h"
#import "OSNotification+Internal.h"
#import "OSMigrationController.h"
#import "OSBackgroundTaskHandlerImpl.h"
#import "OSFocusCallParams.h"
#import <OneSignalNotifications/OneSignalNotifications.h>
#import <OneSignalLocation/OneSignalLocationManager.h>
#import <OneSignalInAppMessages/OneSignalInAppMessages.h>
// TODO: ^ if no longer support ios 9 + 10 after user model, need to address all stuffs
#import <OneSignalOutcomes/OneSignalOutcomes.h>
#import "OneSignalExtension/OneSignalExtension.h"
#import "OSObservable.h"
#import "OSPendingCallbacks.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 <OneSignalUser/OneSignalUser-Swift.h>
// #import <OneSignalUser/OneSignalUser.h>
#import <UserNotifications/UserNotifications.h>
#import "DelayedConsentInitializationParameters.h"
#import "OneSignalDialogController.h"
#import "OneSignalLifecycleObserver.h"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
@interface OneSignal (SessionStatusDelegate)
@end
@implementation OneSignal
// Has attempted to register for push notifications with Apple since app was installed.
static BOOL registeredWithApple = NO;
// 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.
DelayedConsentInitializationParameters *_delayedInitParameters;
+ (DelayedConsentInitializationParameters *)delayedInitParameters {
return _delayedInitParameters;
}
static NSDictionary* launchOptions;
static NSDictionary* appSettings;
// Ensure we only initlize the SDK once even if the public method is called more
// Called after successfully calling setAppId and setLaunchOptions
static BOOL initDone = false;
// Used to track last time SDK was initialized, for whether or not to start a new session
static NSTimeInterval initializationTime;
//// Set when the app is launched
//static NSDate *sessionLaunchTime;
/*
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;
}
+ (NSString*)sdkVersionRaw {
return ONESIGNAL_VERSION;
}
// TODO: Is this method used by wrappers? It is not used by this SDK. Can we remove?
+ (NSString*)sdkSemanticVersion {
// 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];
}
//TODO: This is related to unit tests and will change with um tests
+ (void)clearStatics {
[OneSignalConfigManager setAppId:nil];
launchOptions = false;
appSettings = nil;
initDone = false;
[OSNotificationsManager clearStatics];
registeredWithApple = false;
_downloadedParameters = false;
_didCallDownloadParameters = false;
// sessionLaunchTime = [NSDate date];
[OSOutcomes clearStatics];
[OSSessionManager resetSharedSessionManager];
}
#pragma mark Namespaces
+ (id<OSUser>)User {
return [OneSignalUserManagerImpl.sharedInstance User];
}
+ (void)login:(NSString * _Nonnull)externalId {
// return if no app_id / the user has not granted privacy permissions
if ([OneSignalConfigManager shouldAwaitAppIdAndLogMissingPrivacyConsentForMethod:@"login"]) {
return;
}
[OneSignalUserManagerImpl.sharedInstance loginWithExternalId:externalId token:nil];
// refine Swift name for Obj-C? But doesn't matter as much since this isn't public API
}
+ (void)login:(NSString * _Nonnull)externalId withToken:(NSString * _Nullable)token {
// TODO: Need to await download iOS params
// return if no app_id / the user has not granted privacy permissions
if ([OneSignalConfigManager shouldAwaitAppIdAndLogMissingPrivacyConsentForMethod:@"login"]) {
return;
}
[OneSignalUserManagerImpl.sharedInstance loginWithExternalId:externalId token:token];
}
+ (void)logout {
[OneSignalUserManagerImpl.sharedInstance logout];
}
#pragma mark: Namespaces
+ (Class<OSNotifications>)Notifications {
return [OSNotificationsManager Notifications];
}
+ (Class<OSSession>)Session {
return [OSOutcomes Session];
}
+ (Class<OSInAppMessages>)InAppMessages {
let oneSignalInAppMessages = NSClassFromString(ONE_SIGNAL_IN_APP_MESSAGES_CLASS_NAME);
if (oneSignalInAppMessages != nil && [oneSignalInAppMessages respondsToSelector:@selector(InAppMessages)]) {
return [oneSignalInAppMessages performSelector:@selector(InAppMessages)];
} else {
[OneSignalLog onesignalLog:ONE_S_LL_ERROR message:@"OneSignalInAppMessages not found. In order to use OneSignal's In App Messaging features the OneSignalInAppMessages module must be added."];
return [OSStubInAppMessages InAppMessages];
}
}
+ (Class<OSLiveActivities>)LiveActivities {
return [OneSignalLiveActivityController LiveActivities];
}
+ (Class<OSLocation>)Location {
let oneSignalLocationManager = NSClassFromString(ONE_SIGNAL_LOCATION_CLASS_NAME);
if (oneSignalLocationManager != nil && [oneSignalLocationManager respondsToSelector:@selector(Location)]) {
return [oneSignalLocationManager performSelector:@selector(Location)];
} else {
return [OSStubLocation Location];
}
}
+ (Class<OSDebug>)Debug {
return [OneSignalLog Debug];
}
#pragma mark Initialization
/*
This should be set from all OneSignal entry points.
Note: wrappers may call this method with a null appId.
*/
+ (void)initialize:(nonnull NSString*)newAppId withLaunchOptions:(nullable NSDictionary*)launchOptions {
[self setAppId:newAppId];
[self setLaunchOptions:launchOptions];
[self init];
}
+ (NSString * _Nullable)getCachedAppId {
let prevAppId = [OneSignalUserDefaults.initStandard getSavedStringForKey:OSUD_APP_ID defaultValue:nil];
if (!prevAppId) {
[OneSignalLog onesignalLog:ONE_S_LL_INFO message:@"Waiting for setAppId(appId) with a valid appId to complete OneSignal init!"];
} else {
let logMessage = [NSString stringWithFormat:@"Initializing OneSignal with cached appId: '%@'.", prevAppId];
[OneSignalLog onesignalLog:ONE_S_LL_INFO message:logMessage];
}
return prevAppId;
}
/*
1/2 steps in OneSignal init, relying on setLaunchOptions (usage order does not matter)
Sets the app id OneSignal should use in the application
*/
// TODO: For release, note this change in migration guide:
// No longer reading appID from plist @"OneSignal_APPID" and @"GameThrive_APPID"
+ (void)setAppId:(nullable NSString*)newAppId {
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:[NSString stringWithFormat:@"setAppId called with appId: %@!", newAppId]];
if (!newAppId || newAppId.length == 0) {
NSString* cachedAppId = [self getCachedAppId];
if (cachedAppId) {
[OneSignalConfigManager setAppId:cachedAppId];
} else {
return;
}
} else if ([OneSignalConfigManager getAppId] && ![newAppId isEqualToString:[OneSignalConfigManager getAppId]]) {
// Pre-check on app id to make sure init of SDK is performed properly
// Usually when the app id is changed during runtime so that SDK is reinitialized properly
initDone = false;
[OneSignalConfigManager setAppId:newAppId];
} else {
[OneSignalConfigManager setAppId:newAppId];
}
[self handleAppIdChange:[OneSignalConfigManager getAppId]];
}
+ (BOOL)isValidAppId:(NSString*)appId {
if (!appId || ![[NSUUID alloc] initWithUUIDString:appId]) {
[OneSignalLog onesignalLog:ONE_S_LL_FATAL message:[NSString stringWithFormat:@"OneSignal AppId: %@ - AppId is null or format is invalid, stopping initialization.\nExample usage: 'b2f7f966-d8cc-11e4-bed1-df8f05be55ba'\n", appId]];
return false;
}
return true;
}
/*
1/2 steps in OneSignal init, relying on setAppId (usage order does not matter)
Sets the iOS sepcific app settings
Method must be called to successfully init OneSignal
Note: While this is called via `initialize`, it is also called directly from wrapper SDKs.
*/
+ (void)setLaunchOptions:(nullable NSDictionary*)newLaunchOptions {
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:[NSString stringWithFormat:@"setLaunchOptions() called with launchOptions: %@!", launchOptions.description]];
// Don't continue if the newLaunchOptions are nil
if (!newLaunchOptions) {
return;
}
launchOptions = newLaunchOptions;
// 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)
[OSNotificationsManager setColdStartFromTapOnNotification:YES];
}
+ (void)setProvidesNotificationSettingsView:(BOOL)providesView {
if (providesView && [OSDeviceUtils isIOSVersionGreaterThanOrEqual:@"12.0"]) {
[OSNotificationsManager setProvidesNotificationSettingsView: providesView];
}
}
#pragma mark Initialization
+ (BOOL)shouldStartNewSession {
// return if the user has not granted privacy permissions
if ([OSPrivacyConsentController shouldLogMissingPrivacyConsentErrorWithMethodName:nil])
return false;
// TODO: There used to be many additional checks here but for now, let's omit. Consider adding them or variants later.
// The SDK hasn't finished initializing yet, init() will start the new session
if (!initDone) {
[OneSignalLog onesignalLog:ONE_S_LL_DEBUG message:[NSString stringWithFormat:@"shouldStartNewSession:initDone: %d", initDone]];
return false;
}
NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
NSTimeInterval lastTimeClosed = [OneSignalUserDefaults.initStandard getSavedDoubleForKey:OSUD_APP_LAST_CLOSED_TIME defaultValue:0];
// Make sure last time we closed app was more than 30 secs ago
const int minTimeThreshold = 30;
NSTimeInterval timeSinceLastClosed = now - lastTimeClosed;
NSTimeInterval timeSinceInitialization = now - initializationTime;
[OneSignalLog onesignalLog:ONE_S_LL_DEBUG message:[NSString stringWithFormat:@"shouldStartNewSession:timeSinceLastClosed: %f", timeSinceLastClosed]];
[OneSignalLog onesignalLog:ONE_S_LL_DEBUG message:[NSString stringWithFormat:@"shouldStartNewSession:timeSinceInitialization: %f", timeSinceInitialization]];
return MIN(timeSinceLastClosed, timeSinceInitialization) >= minTimeThreshold;
}
+ (void)startNewSession:(BOOL)fromInit {
// If not called from init, need to check if we should start a new session
if (!fromInit && ![self shouldStartNewSession]) {
return;
}
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:@"startNewSession"];
// Run on the main queue as it is possible for this to be called from multiple queues.
// Also some of the code in the method is not thread safe such as _outcomeEventsController.
[OneSignalHelper dispatch_async_on_main_queue:^{
[self startNewSessionInternal];
}];
}
+ (void)startNewSessionInternal {
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:@"startNewSessionInternal"];
// return if the user has not granted privacy permissions
if ([OSPrivacyConsentController shouldLogMissingPrivacyConsentErrorWithMethodName:nil])
return;
[OSOutcomes.sharedController clearOutcomes];
[[OSSessionManager sharedSessionManager] restartSessionIfNeeded];
[OneSignalTrackFirebaseAnalytics trackInfluenceOpenEvent];
// Clear last location after attaching data to user state or not
let oneSignalLocation = NSClassFromString(ONE_SIGNAL_LOCATION_CLASS_NAME);
if (oneSignalLocation != nil && [oneSignalLocation respondsToSelector:@selector(clearLastLocation)]) {
[oneSignalLocation performSelector:@selector(clearLastLocation)];
}
[OSNotificationsManager sendNotificationTypesUpdateToDelegate];
// TODO: Figure out if Create User also sets session_count automatically on backend
[OneSignalUserManagerImpl.sharedInstance startNewSession];
// This is almost always going to be nil the first time.
// The OSMessagingController is an OSPushSubscriptionObserver so that we pull IAMs once we have the sub id
NSString *subscriptionId = OneSignalUserManagerImpl.sharedInstance.pushSubscriptionId;
if (subscriptionId) {
let oneSignalInAppMessages = NSClassFromString(ONE_SIGNAL_IN_APP_MESSAGES_CLASS_NAME);
if (oneSignalInAppMessages != nil && [oneSignalInAppMessages respondsToSelector:@selector(getInAppMessagesFromServer:)]) {
[oneSignalInAppMessages performSelector:@selector(getInAppMessagesFromServer:) withObject:subscriptionId];
}
}
// The below means there are NO IAMs until on_session returns
// because they can be ended, paused, or deleted from the server, or your segment has changed and you're no longer eligible
// ^ Do the "on_session" call, send session_count++
// on success:
// [OneSignalLocation sendLocation];
// [self executePendingLiveActivityUpdates];
// [self receivedInAppMessageJson:results[@"push"][@"in_app_messages"]]; // go to controller
// on failure:
// [OSMessagingController.sharedInstance updateInAppMessagesFromCache]; // go to controller
}
+ (void)startInAppMessages {
let oneSignalInAppMessages = NSClassFromString(ONE_SIGNAL_IN_APP_MESSAGES_CLASS_NAME);
if (oneSignalInAppMessages != nil && [oneSignalInAppMessages respondsToSelector:@selector(start)]) {
[oneSignalInAppMessages performSelector:@selector(start)];
}
}
+ (void)startOutcomes {
[OSOutcomes start];
[OSOutcomes.sharedController cleanUniqueOutcomeNotifications]; // TODO: should this actually be in new session instead of init
}
+ (void)startLocation {
let oneSignalLocation = NSClassFromString(ONE_SIGNAL_LOCATION_CLASS_NAME);
if (oneSignalLocation != nil && [oneSignalLocation respondsToSelector:@selector(start)]) {
[oneSignalLocation performSelector:@selector(start)];
}
}
+ (void)startTrackFirebaseAnalytics {
if ([OneSignalTrackFirebaseAnalytics libraryExists]) {
[OneSignalTrackFirebaseAnalytics init];
}
}
+ (void)startTrackIAP {
if ([OneSignalTrackIAP canTrack])
[OneSignalTrackIAP sharedInstance]; // start observing purchases
}
+ (void)startLifecycleObserver {
[OneSignalLifecycleObserver registerLifecycleObserver];
}
+ (void)startUserManager {
[OneSignalUserManagerImpl.sharedInstance start];
[OSNotificationsManager sendPushTokenToDelegate];
}
+ (void)delayInitializationForPrivacyConsent {
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:@"Delayed initialization of the OneSignal SDK until the user provides privacy consent using the setPrivacyConsent() method"];
delayedInitializationForPrivacyConsent = true;
_delayedInitParameters = [[DelayedConsentInitializationParameters alloc] initWithLaunchOptions:launchOptions withAppId:[OneSignalConfigManager getAppId]];
// Init was not successful, set appId back to nil
[OneSignalConfigManager setAppId:nil];
}
/*
Called after setAppId and setLaunchOptions, depending on which one is called last (order does not matter)
*/
+ (void)init {
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:[NSString stringWithFormat:@"launchOptions is set and appId of %@ is set, initializing OneSignal...", [OneSignalConfigManager getAppId]]];
// TODO: We moved this check to the top of this method, we should test this.
if (initDone) {
return;
}
[[OSMigrationController new] migrate];
OSBackgroundTaskManager.taskHandler = [OSBackgroundTaskHandlerImpl new];
[self registerForAPNsToken];
// 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 && [OneSignalConfigManager getAppId] && [OneSignalConfigManager getAppId] != (id)[NSNull null])
[self downloadIOSParamsWithAppId:[OneSignalConfigManager getAppId]];
// using classes as delegates is not best practice. We should consider using a shared instance of a class instead
[OSSessionManager sharedSessionManager].delegate = (id<SessionStatusDelegate>)self;
if ([OSPrivacyConsentController requiresUserPrivacyConsent]) {
[self delayInitializationForPrivacyConsent];
return;
}
// Now really initializing the SDK!
// Invalid app ids reaching here will cause failure
if (![self isValidAppId:[OneSignalConfigManager getAppId]])
return;
// TODO: Consider the implications of `registerUserInternal` previously running on the main_queue
// Some of its calls have been moved into `init` here below
/*
// Run on the main queue as it is possible for this to be called from multiple queues.
// Also some of the code in the method is not thread safe such as _outcomeEventsController.
[OneSignalHelper dispatch_async_on_main_queue:^{
[self registerUserInternal];
}];
*/
[OSNotificationsManager clearBadgeCount:false fromClearAll:false];
[self startOutcomes];
[self startLocation];
[self startTrackIAP];
[self startTrackFirebaseAnalytics];
[self startLifecycleObserver];
//TODO: Should these be started in Dependency order? e.g. IAM depends on User Manager shared instance
[self startUserManager]; // By here, app_id exists, and consent is granted.
[self startInAppMessages];
[self startNewSession:YES];
initializationTime = [[NSDate date] timeIntervalSince1970];
initDone = true;
}
+ (NSString *)appGroupKey {
return [OneSignalUserDefaults appGroupName];
}
+ (void)handleAppIdChange:(NSString*)appId {
// 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]) {
[OneSignalLog onesignalLog:ONE_S_LL_WARN message:@"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];
// 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 (appId && ![appId isEqualToString:prevAppId]) {
initDone = false;
_downloadedParameters = false;
_didCallDownloadParameters = false;
let sharedUserDefaults = OneSignalUserDefaults.initShared;
[standardUserDefaults saveStringForKey:OSUD_APP_ID withValue:appId];
// Remove player_id from both standard and shared NSUserDefaults
[standardUserDefaults removeValueForKey:OSUD_PUSH_SUBSCRIPTION_ID];
[sharedUserDefaults removeValueForKey:OSUD_PUSH_SUBSCRIPTION_ID];
[standardUserDefaults removeValueForKey:OSUD_LEGACY_PLAYER_ID];
[sharedUserDefaults removeValueForKey:OSUD_LEGACY_PLAYER_ID];
// Clear all cached data, does not start User Module nor call logout.
[OneSignalUserManagerImpl.sharedInstance clearAllModelsFromStores];
}
// Always save appId 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:appId];
}
+ (void)registerForAPNsToken {
registeredWithApple = OSNotificationsManager.currentPermissionState.accepted;
// Register with Apple's APNS server if we registed once before or if auto-prompt hasn't been disabled.
if (registeredWithApple && !OSNotificationsManager.currentPermissionState.ephemeral) {
[OSNotificationsManager requestPermission:nil];
} else {
[OSNotificationsManager checkProvisionalAuthorizationStatus];
[OSNotificationsManager registerForAPNsToken];
}
}
+ (void)setConsentRequired:(BOOL)required {
[OSPrivacyConsentController setRequiresPrivacyConsent:required];
}
+ (void)setConsentGiven:(BOOL)granted {
[OSPrivacyConsentController consentGranted:granted];
if (!granted || !delayedInitializationForPrivacyConsent || _delayedInitParameters == nil)
return;
// Try to init again using delayed params
[self initialize:_delayedInitParameters.appId withLaunchOptions:_delayedInitParameters.launchOptions];
delayedInitializationForPrivacyConsent = false;
_delayedInitParameters = nil;
}
+ (BOOL)getPrivacyConsent {
return [OSPrivacyConsentController getPrivacyConsent];
}
+ (void)downloadIOSParamsWithAppId:(NSString *)appId {
[OneSignalLog onesignalLog:ONE_S_LL_DEBUG message:@"Downloading iOS parameters for this application"];
_didCallDownloadParameters = true;
// This will be nil unless we have a cached user
// TODO: Commented out. This will init the User Manager too early, and userId is not needed anyway.
// NSString *userId = OneSignalUserManagerImpl.sharedInstance.pushSubscriptionId;
NSString *userId = nil;
[OneSignalClient.sharedClient executeRequest:[OSRequestGetIosParams withUserId:userId appId:appId] onSuccess:^(NSDictionary *result) {
if (result[IOS_REQUIRES_USER_ID_AUTHENTICATION]) {
OneSignalUserManagerImpl.sharedInstance.requiresUserAuth = [result[IOS_REQUIRES_USER_ID_AUTHENTICATION] boolValue];
}
if (result[IOS_USES_PROVISIONAL_AUTHORIZATION] != (id)[NSNull null]) {
[OneSignalUserDefaults.initStandard saveBoolForKey:OSUD_USES_PROVISIONAL_PUSH_AUTHORIZATION withValue:[result[IOS_USES_PROVISIONAL_AUTHORIZATION] boolValue]];
[OSNotificationsManager checkProvisionalAuthorizationStatus];
}
if (result[IOS_RECEIVE_RECEIPTS_ENABLE] != (id)[NSNull null])
[OneSignalUserDefaults.initShared saveBoolForKey:OSUD_RECEIVE_RECEIPTS_ENABLED withValue:[result[IOS_RECEIVE_RECEIPTS_ENABLE] boolValue]];
[[OSRemoteParamController sharedController] saveRemoteParams:result];
if ([[OSRemoteParamController sharedController] hasLocationKey]) {
BOOL shared = [result[IOS_LOCATION_SHARED] boolValue];
let oneSignalLocation = NSClassFromString(ONE_SIGNAL_LOCATION_CLASS_NAME);
if (oneSignalLocation != nil && [oneSignalLocation respondsToSelector:@selector(startLocationSharedWithFlag:)]) {
[OneSignalCoreHelper callSelector:@selector(startLocationSharedWithFlag:) onObject:oneSignalLocation withArg:shared];
}
}
if ([[OSRemoteParamController sharedController] hasPrivacyConsentKey]) {
BOOL required = [result[IOS_REQUIRES_USER_PRIVACY_CONSENT] boolValue];
[[OSRemoteParamController sharedController] savePrivacyConsentRequired:required];
[OSPrivacyConsentController setRequiresPrivacyConsent:required];
}
if (result[OUTCOMES_PARAM] && result[OUTCOMES_PARAM][IOS_OUTCOMES_V2_SERVICE_ENABLE])
[[OSOutcomeEventsCache sharedOutcomeEventsCache] saveOutcomesV2ServiceEnabled:[result[OUTCOMES_PARAM][IOS_OUTCOMES_V2_SERVICE_ENABLE] boolValue]];
[[OSTrackerFactory sharedTrackerFactory] saveInfluenceParams:result];
[OneSignalTrackFirebaseAnalytics updateFromDownloadParams:result];
_downloadedParameters = true;
} onFailure:^(NSError *error) {
_didCallDownloadParameters = false;
}];
}
//TODO: consolidate in one place. Where???
+ (void)launchWebURL:(NSString*)openUrl {
NSString* toOpenUrl = [OneSignalCoreHelper trimURLSpacing:openUrl];
if (toOpenUrl && [OneSignalCoreHelper verifyURL:toOpenUrl]) {
NSURL *url = [NSURL URLWithString:toOpenUrl];
// Give the app resume animation time to finish when tapping on a notification from the notification center.
// Isn't a requirement but improves visual flow.
[OneSignalHelper performSelector:@selector(displayWebView:) withObject:url afterDelay:0.5];
}
}
// Called from the app's Notification Service Extension
+ (UNMutableNotificationContent*)didReceiveNotificationExtensionRequest:(UNNotificationRequest*)request withMutableNotificationContent:(UNMutableNotificationContent*)replacementContent {
return [OneSignalNotificationServiceExtensionHandler
didReceiveNotificationExtensionRequest:request
withMutableNotificationContent:replacementContent];
}
// Called from the app's Notification Service Extension. Calls contentHandler() to display the notification
+ (UNMutableNotificationContent*)didReceiveNotificationExtensionRequest:(UNNotificationRequest*)request withMutableNotificationContent:(UNMutableNotificationContent*)replacementContent
withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
return [OneSignalNotificationServiceExtensionHandler
didReceiveNotificationExtensionRequest:request
withMutableNotificationContent:replacementContent
withContentHandler:contentHandler];
}
// Called from the app's Notification Service Extension
+ (UNMutableNotificationContent*)serviceExtensionTimeWillExpireRequest:(UNNotificationRequest*)request withMutableNotificationContent:(UNMutableNotificationContent*)replacementContent {
return [OneSignalNotificationServiceExtensionHandler
serviceExtensionTimeWillExpireRequest:request
withMutableNotificationContent:replacementContent];
}
//
////TODO: move to sessions/onfocus
//+ (NSDate *)sessionLaunchTime {
// return sessionLaunchTime;
//}
/*
Start of outcome module
*/
+ (void)sendSessionEndOutcomes:(NSNumber*)totalTimeActive params:(OSFocusCallParams *)params onSuccess:(OSResultSuccessBlock _Nonnull)successBlock onFailure:(OSFailureBlock _Nonnull)failureBlock {
if (![OSOutcomes sharedController]) {
[OneSignalLog onesignalLog:ONE_S_LL_ERROR message:@"Make sure OneSignal init is called first"];
if (failureBlock) {
failureBlock([NSError errorWithDomain:@"onesignal" code:0 userInfo:@{@"error" : @"Missing outcomes controller."}]);
}
return;
}
NSString* onesignalId = OneSignalUserManagerImpl.sharedInstance.onesignalId;
NSString* pushSubscriptionId = OneSignalUserManagerImpl.sharedInstance.pushSubscriptionId;
if (!onesignalId || !pushSubscriptionId) {
if (failureBlock) {
failureBlock([NSError errorWithDomain:@"onesignal" code:0 userInfo:@{@"error" : @"Missing onesignalId or pushSubscriptionId."}]);
}
return;
}
[OSOutcomes.sharedController sendSessionEndOutcomes:totalTimeActive
appId:[OneSignalConfigManager getAppId]
pushSubscriptionId:pushSubscriptionId
onesignalId:onesignalId
influenceParams:params.influenceParams
onSuccess:successBlock
onFailure:failureBlock];
}
@end
@implementation OneSignal (SessionStatusDelegate)
+ (void)onSessionEnding:(NSArray<OSInfluence *> *)lastInfluences {
if ([OSOutcomes sharedController])
[OSOutcomes.sharedController clearOutcomes];
[OneSignalTracker onSessionEnded:lastInfluences];
}
@end
/*
End of outcome module
*/
// Swizzles UIApplication class to swizzling the following:
// - UIApplication
// - setDelegate:
// - Used to swizzle all UIApplicationDelegate selectors on the passed in class.
// - Almost always this is the AppDelegate class but since UIApplicationDelegate is an "interface" this could be any class.
// - UNUserNotificationCenter
// - setDelegate:
// - For iOS 10 only, swizzle all UNUserNotificationCenterDelegate selectors on the passed in class.
// - This may or may not be set so we set our own now in registerAsUNNotificationCenterDelegate to an empty class.
//
// Note1: Do NOT move this category to it's own file. This is required so when the app developer calls OneSignal.initWithLaunchOptions this load+
// will fire along with it. This is due to how iOS loads .m files into memory instead of classes.
// Note2: Do NOT directly add swizzled selectors to this category as if this class is loaded into the runtime twice unexpected results will occur.
// The oneSignalLoadedTagSelector: selector is used a flag to prevent double swizzling if this library is loaded twice.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wincomplete-implementation"
@implementation UIApplication (OneSignal)
+ (void)load {
if ([self shouldDisableBasedOnProcessArguments]) {
[OneSignalLog onesignalLog:ONE_S_LL_WARN message:@"OneSignal method swizzling is disabled. Make sure the feature is enabled for production."];
return;
}
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:@"UIApplication(OneSignal) LOADED!"];
// Prevent Xcode storyboard rendering process from crashing with custom IBDesignable Views or from hostless unit tests or share-extension.
// https://github.com/OneSignal/OneSignal-iOS-SDK/issues/160
// https://github.com/OneSignal/OneSignal-iOS-SDK/issues/935
// https://github.com/OneSignal/OneSignal-iOS-SDK/issues/1073
NSProcessInfo *processInfo = [NSProcessInfo processInfo];
NSString *processName = [processInfo processName];
NSString *infoPath = [[processInfo arguments] objectAtIndex:0];
if ([processName isEqualToString:@"IBDesignablesAgentCocoaTouch"] || [processName isEqualToString:@"IBDesignablesAgent-iOS"] || [processName isEqualToString:@"xctest"] || ([infoPath rangeOfString: @".appex"].location != NSNotFound))
return;
// Double loading of class detection.
BOOL existing = injectSelector(
self,
@selector(oneSignalLoadedTagSelector:),
[OneSignalAppDelegate class],
@selector(oneSignalLoadedTagSelector:)
);
if (existing) {
[OneSignalLog onesignalLog:ONE_S_LL_WARN message:@"Already swizzled UIApplication.setDelegate. Make sure the OneSignal library wasn't loaded into the runtime twice!"];
return;
}
[OSNotificationsManager start];
[[OSMigrationController new] migrate];
// sessionLaunchTime = [NSDate date];
// TODO: sessionLaunchTime used to always be set in load
[OSDialogInstanceManager setSharedInstance:[OneSignalDialogController sharedInstance]];
}
/*
In order for the badge count to be consistent even in situations where the developer manually sets the badge number,
We swizzle the 'setApplicationIconBadgeNumber()' to intercept these calls so we always know the latest count
*/
- (void)onesignalSetApplicationIconBadgeNumber:(NSInteger)badge {
[OneSignalExtensionBadgeHandler updateCachedBadgeValue:badge];
[self onesignalSetApplicationIconBadgeNumber:badge];
}
+(BOOL) shouldDisableBasedOnProcessArguments {
if ([NSProcessInfo.processInfo.arguments containsObject:@"DISABLE_ONESIGNAL_SWIZZLING"]) {
return YES;
}
return NO;
}
@end
#pragma clang diagnostic pop
#pragma clang diagnostic pop
#pragma clang diagnostic pop