-
Notifications
You must be signed in to change notification settings - Fork 262
/
OneSignal.m
executable file
·1372 lines (1054 loc) · 56.4 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
/**
* Copyright 2015 OneSignal
* Portions Copyright 2014 StackMob
*
* This file includes portions from the StackMob iOS SDK and distributed under an Apache 2.0 license.
* StackMob was acquired by PayPal and ceased operation on May 22, 2014.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "OneSignal.h"
#import "OneSignalHTTPClient.h"
#import "OneSignalTrackIAP.h"
#import "OneSignalJailbreakDetection.h"
#import "OneSignalReachability.h"
#import "OneSignalMobileProvision.h"
#import <stdlib.h>
#import <stdio.h>
#import <sys/types.h>
#import <sys/sysctl.h>
#import <sys/utsname.h>
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
#define DEFAULT_PUSH_HOST @"https://onesignal.com/api/v1/"
#define NOTIFICATION_TYPE_BADGE 1
#define NOTIFICATION_TYPE_SOUND 2
#define NOTIFICATION_TYPE_ALERT 4
#define NOTIFICATION_TYPE_ALL 7
static OneSignal* defaultClient = nil;
static ONE_S_LOG_LEVEL _nsLogLevel = ONE_S_LL_WARN;
static ONE_S_LOG_LEVEL _visualLogLevel = ONE_S_LL_NONE;
@interface OneSignalAlertViewDelegate : NSObject<UIAlertViewDelegate>
- (id)initWithMessageDict:(NSDictionary*)messageDict OneSignal:oneSignal;
@end
@interface OneSignal ()
@property(nonatomic, readwrite, copy) NSString *app_id;
@property(nonatomic, readwrite, copy) NSDictionary *lastMessageReceived;
@property(nonatomic, readwrite, copy) NSString *deviceModel;
@property(nonatomic, readwrite, copy) NSString *systemVersion;
@property(nonatomic, retain) OneSignalHTTPClient *httpClient;
@end
@implementation OneSignal
NSString* const ONESIGNAL_VERSION = @"011100";
@synthesize app_id = _GT_publicKey;
@synthesize httpClient = _GT_httpRequest;
@synthesize lastMessageReceived;
NSMutableDictionary* tagsToSend;
NSString* mDeviceToken;
OneSignalResultSuccessBlock tokenUpdateSuccessBlock;
OneSignalFailureBlock tokenUpdateFailureBlock;
NSString* mUserId;
OneSignalIdsAvailableBlock idsAvailableBlockWhenReady;
OneSignalHandleNotificationBlock handleNotification;
UIBackgroundTaskIdentifier focusBackgroundTask;
OneSignalTrackIAP* trackIAPPurchase;
bool registeredWithApple = false; // Has attempted to register for push notifications with Apple.
bool oneSignalReg = false;
bool waitingForOneSReg = false;
NSNumber* lastTrackedTime;
NSNumber* unSentActiveTime;
NSNumber* timeToPingWith;
int mNotificationTypes = -1;
bool mSubscriptionSet = true;
static NSString* mSDKType = @"native";
+ (void)setMSDKType:(NSString*)str {
mSDKType = str;
}
- (id)initWithLaunchOptions:(NSDictionary*)launchOptions {
return [self initWithLaunchOptions:launchOptions appId:nil handleNotification:nil autoRegister:true];
}
- (id)initWithLaunchOptions:(NSDictionary*)launchOptions autoRegister:(BOOL)autoRegister {
return [self initWithLaunchOptions:launchOptions appId:nil handleNotification:nil autoRegister:autoRegister];
}
- (id)initWithLaunchOptions:(NSDictionary*)launchOptions appId:(NSString*)appId {
return [self initWithLaunchOptions:launchOptions appId:appId handleNotification:nil autoRegister:true];
}
- (id)initWithLaunchOptions:(NSDictionary*)launchOptions handleNotification:(OneSignalHandleNotificationBlock)callback {
return [self initWithLaunchOptions:launchOptions appId:nil handleNotification:callback autoRegister:true];
}
- (id)initWithLaunchOptions:(NSDictionary*)launchOptions appId:(NSString*)appId handleNotification:(OneSignalHandleNotificationBlock)callback {
return [self initWithLaunchOptions:launchOptions appId:appId handleNotification:callback autoRegister:true];
}
- (id)initWithLaunchOptions:(NSDictionary*)launchOptions appId:(NSString*)appId handleNotification:(OneSignalHandleNotificationBlock)callback autoRegister:(BOOL)autoRegister {
self = [super init];
if (NSFoundationVersionNumber < NSFoundationVersionNumber_iOS_6_0)
return self;
if (![[NSUUID alloc] initWithUUIDString:appId]) {
onesignal_Log(ONE_S_LL_FATAL, @"OneSignal AppId format is invalid.\nExample: 'b2f7f966-d8cc-11eg-bed1-df8f05be55ba'\n");
return self;
}
if ([@"b2f7f966-d8cc-11eg-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");
if (self) {
handleNotification = callback;
unSentActiveTime = [NSNumber numberWithInteger:-1];
lastTrackedTime = [NSNumber numberWithLongLong:[[NSDate date] timeIntervalSince1970]];
if (appId)
self.app_id = appId;
else {
self.app_id = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"OneSignal_APPID"];
if (self.app_id == nil)
self.app_id = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"GameThrive_APPID"];
}
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@", DEFAULT_PUSH_HOST]];
self.httpClient = [[OneSignalHTTPClient alloc] initWithBaseURL:url];
struct utsname systemInfo;
uname(&systemInfo);
self.deviceModel = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
self.systemVersion = [[UIDevice currentDevice] systemVersion];
if (defaultClient == nil)
defaultClient = self;
// Handle changes to the app id. This might happen on a developer's device when testing.
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
if (self.app_id == nil)
self.app_id = [defaults stringForKey:@"GT_APP_ID"];
else if (![self.app_id isEqualToString:[defaults stringForKey:@"GT_APP_ID"]]) {
[defaults setObject:self.app_id forKey:@"GT_APP_ID"];
[defaults setObject:nil forKey:@"GT_PLAYER_ID"];
[defaults synchronize];
}
mUserId = [defaults stringForKey:@"GT_PLAYER_ID"];
mDeviceToken = [defaults stringForKey:@"GT_DEVICE_TOKEN"];
if (([[UIApplication sharedApplication] respondsToSelector:@selector(currentUserNotificationSettings)]))
registeredWithApple = [[UIApplication sharedApplication] currentUserNotificationSettings].types != (NSUInteger)nil;
else
registeredWithApple = mDeviceToken != nil || [defaults boolForKey:@"GT_REGISTERED_WITH_APPLE"];
mSubscriptionSet = [defaults objectForKey:@"ONESIGNAL_SUBSCRIPTION"] == nil;
mNotificationTypes = getNotificationTypes();
// Register this device with Apple's APNS server.
if (autoRegister || registeredWithApple)
[self registerForPushNotifications];
// iOS 8 - Register for remote notifications to get a token now since registerUserNotificationSettings is what shows the prompt.
else if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerForRemoteNotifications)])
[[UIApplication sharedApplication] registerForRemoteNotifications];
if (mUserId != nil)
[self registerUser];
else // Fall back incase Apple does not responsed in time.
[self performSelector:@selector(registerUser) withObject:nil afterDelay:30.0f];
}
NSDictionary* userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (userInfo && NSFoundationVersionNumber < NSFoundationVersionNumber_iOS_7_0) {
// Only call for iOS 6.
// In iOS 7 & 8 the fetchCompletionHandler gets called inaddition to userInfo being filled here.
[self notificationOpened:userInfo isActive:false];
}
clearBadgeCount(false);
if ([OneSignalTrackIAP canTrack])
trackIAPPurchase = [[OneSignalTrackIAP alloc] init];
return self;
}
+ (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, 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) {
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:levelString
message:message
delegate:nil
cancelButtonTitle:@"Close"
otherButtonTitles:nil, nil];
[alertView show];
}
}
// "registerForRemoteNotifications*" calls didRegisterForRemoteNotificationsWithDeviceToken
// in the implementation UIApplication(OneSignalPush) below after contacting Apple's server.
- (void)registerForPushNotifications {
if (NSFoundationVersionNumber < NSFoundationVersionNumber_iOS_6_0)
return;
// For iOS 8 devices
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
// ClassFromString to work around pre Xcode 6 link errors when building an app using the OneSignal framework.
Class uiUserNotificationSettings = NSClassFromString(@"UIUserNotificationSettings");
NSUInteger notificationTypes = NOTIFICATION_TYPE_ALL;
[[UIApplication sharedApplication] registerUserNotificationSettings:[uiUserNotificationSettings settingsForTypes:notificationTypes categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
else { // For iOS 6 & 7 devices
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
if (!registeredWithApple) {
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:@YES forKey:@"GT_REGISTERED_WITH_APPLE"];
[defaults synchronize];
}
}
}
- (void)registerDeviceToken:(id)inDeviceToken onSuccess:(OneSignalResultSuccessBlock)successBlock onFailure:(OneSignalFailureBlock)failureBlock {
[self updateDeviceToken:inDeviceToken onSuccess:successBlock onFailure:failureBlock];
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:mDeviceToken forKey:@"GT_DEVICE_TOKEN"];
[defaults synchronize];
}
- (void)updateDeviceToken:(NSString*)deviceToken onSuccess:(OneSignalResultSuccessBlock)successBlock onFailure:(OneSignalFailureBlock)failureBlock {
if (mUserId == nil) {
mDeviceToken = deviceToken;
tokenUpdateSuccessBlock = successBlock;
tokenUpdateFailureBlock = failureBlock;
// iOS 8 - We get a token right away but give the user 30 sec to responsed to the system prompt.
// Also check mNotificationTypes so there is no waiting if user has already answered the system prompt.
// The goal is to only have 1 server call.
if (isCapableOfGettingNotificationTypes() && mNotificationTypes == -1) {
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(registerUser) object:nil];
[self performSelector:@selector(registerUser) withObject:nil afterDelay:30.0f];
}
else
[self registerUser];
return;
}
if ([deviceToken isEqualToString:mDeviceToken]) {
if (successBlock)
successBlock(nil);
return;
}
mDeviceToken = deviceToken;
NSMutableURLRequest* request;
request = [self.httpClient requestWithMethod:@"PUT" path:[NSString stringWithFormat:@"players/%@", mUserId]];
NSDictionary* dataDic = [NSDictionary dictionaryWithObjectsAndKeys:
self.app_id, @"app_id",
deviceToken, @"identifier",
nil];
onesignal_Log(ONE_S_LL_VERBOSE, @"Calling OneSignal PUT updated pushToken!");
NSData* postData = [NSJSONSerialization dataWithJSONObject:dataDic options:0 error:nil];
[request setHTTPBody:postData];
[self enqueueRequest:request onSuccess:successBlock onFailure:failureBlock];
if (idsAvailableBlockWhenReady) {
mNotificationTypes = getNotificationTypes();
if (getUsableDeviceToken())
idsAvailableBlockWhenReady(mUserId, getUsableDeviceToken());
idsAvailableBlockWhenReady = nil;
}
}
- (NSArray*)getSoundFiles {
NSFileManager* fm = [NSFileManager defaultManager];
NSError* error = nil;
NSArray* allFiles = [fm contentsOfDirectoryAtPath:[[NSBundle mainBundle] resourcePath] error:&error];
NSMutableArray* soundFiles = [NSMutableArray new];
if (error == nil) {
for(id file in allFiles) {
if ([file hasSuffix:@".wav"] || [file hasSuffix:@".mp3"])
[soundFiles addObject:file];
}
}
return soundFiles;
}
NSNumber* getNetType() {
OneSignalReachability* reachability = [OneSignalReachability reachabilityForInternetConnection];
NetworkStatus status = [reachability currentReachabilityStatus];
if (status == ReachableViaWiFi)
return @0;
return @1;
}
- (void)registerUser {
// Make sure we only call create or on_session once per run of the app.
if (oneSignalReg || waitingForOneSReg)
return;
waitingForOneSReg = true;
NSMutableURLRequest* request;
if (mUserId == nil)
request = [self.httpClient requestWithMethod:@"POST" path:@"players"];
else
request = [self.httpClient requestWithMethod:@"POST" path:[NSString stringWithFormat:@"players/%@/on_session", mUserId]];
NSDictionary* infoDictionary = [[NSBundle mainBundle]infoDictionary];
NSString* build = infoDictionary[(NSString*)kCFBundleVersionKey];
NSMutableDictionary* dataDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:
self.app_id, @"app_id",
self.deviceModel, @"device_model",
self.systemVersion, @"device_os",
[[NSLocale preferredLanguages] objectAtIndex:0], @"language",
[NSNumber numberWithInt:(int)[[NSTimeZone localTimeZone] secondsFromGMT]], @"timezone",
build, @"game_version",
[NSNumber numberWithInt:0], @"device_type",
[[[UIDevice currentDevice] identifierForVendor] UUIDString], @"ad_id",
[self getSoundFiles], @"sounds",
ONESIGNAL_VERSION, @"sdk",
mDeviceToken, @"identifier", // identifier MUST be at the end as it could be nil.
nil];
mNotificationTypes = getNotificationTypes();
if ([OneSignalJailbreakDetection isJailbroken])
dataDic[@"rooted"] = @YES;
dataDic[@"net_type"] = getNetType();
if (mUserId == nil) {
dataDic[@"sdk_type"] = mSDKType;
dataDic[@"ios_bundle"] = [[NSBundle mainBundle] bundleIdentifier];
}
if (mNotificationTypes != -1)
dataDic[@"notification_types"] = [NSNumber numberWithInt:mNotificationTypes];
Class ASIdentifierManagerClass = NSClassFromString(@"ASIdentifierManager");
if (ASIdentifierManagerClass) {
id asIdManager = [ASIdentifierManagerClass valueForKey:@"sharedManager"];
if ([[asIdManager valueForKey:@"advertisingTrackingEnabled"] isEqual:[NSNumber numberWithInt:1]])
dataDic[@"as_id"] = [[asIdManager valueForKey:@"advertisingIdentifier"] UUIDString];
else
dataDic[@"as_id"] = @"OptedOut";
}
UIApplicationReleaseMode releaseMode = [OneSignalMobileProvision releaseMode];
if (releaseMode == UIApplicationReleaseDev || releaseMode == UIApplicationReleaseAdHoc)
dataDic[@"test_type"] = [NSNumber numberWithInt:releaseMode];
onesignal_Log(ONE_S_LL_VERBOSE, @"Calling OneSignal create/on_session");
NSData* postData = [NSJSONSerialization dataWithJSONObject:dataDic options:0 error:nil];
[request setHTTPBody:postData];
[self enqueueRequest:request onSuccess:^(NSDictionary* results) {
oneSignalReg = true;
waitingForOneSReg = false;
if ([results objectForKey:@"id"] != nil) {
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
mUserId = [results objectForKey:@"id"];
[defaults setObject:mUserId forKey:@"GT_PLAYER_ID"];
[defaults synchronize];
if (mDeviceToken)
[self updateDeviceToken:mDeviceToken onSuccess:tokenUpdateSuccessBlock onFailure:tokenUpdateFailureBlock];
if (tagsToSend != nil) {
[self sendTags:tagsToSend];
tagsToSend = nil;
}
if (idsAvailableBlockWhenReady) {
idsAvailableBlockWhenReady(mUserId, getUsableDeviceToken());
if (getUsableDeviceToken())
idsAvailableBlockWhenReady = nil;
}
}
} onFailure:^(NSError* error) {
oneSignalReg = false;
waitingForOneSReg = false;
onesignal_Log(ONE_S_LL_ERROR, [NSString stringWithFormat: @"Error registering with OneSignal: %@", error]);
}];
}
- (void)IdsAvailable:(OneSignalIdsAvailableBlock)idsAvailableBlock {
if (mUserId)
idsAvailableBlock(mUserId, getUsableDeviceToken());
if (mUserId == nil || getUsableDeviceToken() == nil)
idsAvailableBlockWhenReady = idsAvailableBlock;
}
NSString* getUsableDeviceToken() {
if (mNotificationTypes > 0)
return mDeviceToken;
return nil;
}
- (void)sendTagsWithJsonString:(NSString*)jsonString {
NSError* jsonError;
NSData* data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* keyValuePairs = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if (jsonError == nil)
[self sendTags:keyValuePairs];
else {
onesignal_Log(ONE_S_LL_WARN,[NSString stringWithFormat: @"sendTags JSON Parse Error: %@", jsonError]);
onesignal_Log(ONE_S_LL_WARN,[NSString stringWithFormat: @"sendTags JSON Parse Error, JSON: %@", jsonString]);
}
}
- (void)sendTags:(NSDictionary*)keyValuePair {
[self sendTags:keyValuePair onSuccess:nil onFailure:nil];
}
- (void)sendTags:(NSDictionary*)keyValuePair onSuccess:(OneSignalResultSuccessBlock)successBlock onFailure:(OneSignalFailureBlock)failureBlock {
if (NSFoundationVersionNumber < NSFoundationVersionNumber_iOS_6_0)
return;
if (mUserId == nil) {
if (tagsToSend == nil)
tagsToSend = [keyValuePair mutableCopy];
else
[tagsToSend addEntriesFromDictionary:keyValuePair];
return;
}
NSMutableURLRequest* request = [self.httpClient requestWithMethod:@"PUT" path:[NSString stringWithFormat:@"players/%@", mUserId]];
NSDictionary* dataDic = [NSDictionary dictionaryWithObjectsAndKeys:
self.app_id, @"app_id",
keyValuePair, @"tags",
getNetType(), @"net_type",
nil];
NSData* postData = [NSJSONSerialization dataWithJSONObject:dataDic options:0 error:nil];
[request setHTTPBody:postData];
[self enqueueRequest:request
onSuccess:successBlock
onFailure:failureBlock];
}
- (void)sendTag:(NSString*)key value:(NSString*)value {
[self sendTag:key value:value onSuccess:nil onFailure:nil];
}
- (void)sendTag:(NSString*)key value:(NSString*)value onSuccess:(OneSignalResultSuccessBlock)successBlock onFailure:(OneSignalFailureBlock)failureBlock {
[self sendTags:[NSDictionary dictionaryWithObjectsAndKeys: value, key, nil] onSuccess:successBlock onFailure:failureBlock];
}
- (void)getTags:(OneSignalResultSuccessBlock)successBlock onFailure:(OneSignalFailureBlock)failureBlock {
if (NSFoundationVersionNumber < NSFoundationVersionNumber_iOS_6_0 || mUserId == nil)
return;
NSMutableURLRequest* request;
request = [self.httpClient requestWithMethod:@"GET" path:[NSString stringWithFormat:@"players/%@", mUserId]];
[self enqueueRequest:request onSuccess:^(NSDictionary* results) {
if ([results objectForKey:@"tags"] != nil)
successBlock([results objectForKey:@"tags"]);
} onFailure:failureBlock];
}
- (void)getTags:(OneSignalResultSuccessBlock)successBlock {
[self getTags:successBlock onFailure:nil];
}
- (void)deleteTag:(NSString*)key onSuccess:(OneSignalResultSuccessBlock)successBlock onFailure:(OneSignalFailureBlock)failureBlock {
[self deleteTags:@[key] onSuccess:successBlock onFailure:failureBlock];
}
- (void)deleteTag:(NSString*)key {
[self deleteTags:@[key] onSuccess:nil onFailure:nil];
}
- (void)deleteTags:(NSArray*)keys onSuccess:(OneSignalResultSuccessBlock)successBlock onFailure:(OneSignalFailureBlock)failureBlock {
if (NSFoundationVersionNumber < NSFoundationVersionNumber_iOS_6_0 || mUserId == nil)
return;
NSMutableURLRequest* request;
request = [self.httpClient requestWithMethod:@"PUT" path:[NSString stringWithFormat:@"players/%@", mUserId]];
NSMutableDictionary* deleteTagsDict = [NSMutableDictionary dictionary];
for(id key in keys)
[deleteTagsDict setObject:@"" forKey:key];
NSDictionary* dataDic = [NSDictionary dictionaryWithObjectsAndKeys:
self.app_id, @"app_id",
deleteTagsDict, @"tags",
nil];
NSData* postData = [NSJSONSerialization dataWithJSONObject:dataDic options:0 error:nil];
[request setHTTPBody:postData];
[self enqueueRequest:request onSuccess:successBlock onFailure:failureBlock];
}
- (void)deleteTags:(NSArray*)keys {
[self deleteTags:keys onSuccess:nil onFailure:nil];
}
- (void)deleteTagsWithJsonString:(NSString*)jsonString {
NSError* jsonError;
NSData* data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSArray* keys = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
if (jsonError == nil)
[self deleteTags:keys];
else {
onesignal_Log(ONE_S_LL_WARN,[NSString stringWithFormat: @"deleteTags JSON Parse Error: %@", jsonError]);
onesignal_Log(ONE_S_LL_WARN,[NSString stringWithFormat: @"deleteTags JSON Parse Error, JSON: %@", jsonString]);
}
}
- (void) sendNotificationTypesUpdateIsConfirmed:(BOOL)isConfirm {
// User changed notification settings for the app.
if (mNotificationTypes != -1 && mUserId && (isConfirm || mNotificationTypes != getNotificationTypes()) ) {
mNotificationTypes = getNotificationTypes();
NSMutableURLRequest* request = [self.httpClient requestWithMethod:@"PUT" path:[NSString stringWithFormat:@"players/%@", mUserId]];
NSDictionary* dataDic = [NSDictionary dictionaryWithObjectsAndKeys:
self.app_id, @"app_id",
[NSNumber numberWithInt:mNotificationTypes], @"notification_types",
nil];
NSData* postData = [NSJSONSerialization dataWithJSONObject:dataDic options:0 error:nil];
[request setHTTPBody:postData];
[self enqueueRequest:request onSuccess:nil onFailure:nil];
if (getUsableDeviceToken() && idsAvailableBlockWhenReady) {
idsAvailableBlockWhenReady(mUserId, getUsableDeviceToken());
idsAvailableBlockWhenReady = nil;
}
}
}
- (void) beginBackgroundFocusTask {
focusBackgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[self endBackgroundFocusTask];
}];
}
- (void) endBackgroundFocusTask {
[[UIApplication sharedApplication] endBackgroundTask: focusBackgroundTask];
focusBackgroundTask = UIBackgroundTaskInvalid;
}
- (void)onFocus:(NSString*)state {
bool wasBadgeSet = false;
if ([state isEqualToString:@"resume"]) {
lastTrackedTime = [NSNumber numberWithLongLong:[[NSDate date] timeIntervalSince1970]];
[self sendNotificationTypesUpdateIsConfirmed:false];
wasBadgeSet = clearBadgeCount(false);
}
else {
NSNumber* timeElapsed = @(([[NSDate date] timeIntervalSince1970] - [lastTrackedTime longLongValue]) + 0.5);
if ([timeElapsed intValue] < 0 || [timeElapsed intValue] > 604800)
return;
NSNumber* unSentActiveTime = [self getUnsentActiveTime];
NSNumber* totalTimeActive = @([unSentActiveTime intValue] + [timeElapsed intValue]);
if ([totalTimeActive intValue] < 30) {
[self saveUnsentActiveTime:totalTimeActive];
return;
}
timeToPingWith = totalTimeActive;
}
if (mUserId == nil)
return;
// If resuming and badge was set, clear it on the server as well.
if (wasBadgeSet && [state isEqualToString:@"resume"]) {
NSMutableURLRequest* request = [self.httpClient requestWithMethod:@"PUT" path:[NSString stringWithFormat:@"players/%@", mUserId]];
NSDictionary* dataDic = [NSDictionary dictionaryWithObjectsAndKeys:
self.app_id, @"app_id",
@0, @"badge_count",
nil];
NSData* postData = [NSJSONSerialization dataWithJSONObject:dataDic options:0 error:nil];
[request setHTTPBody:postData];
[self enqueueRequest:request onSuccess:nil onFailure:nil];
return;
}
// Update the playtime on the server when the app put into the background or the device goes to sleep mode.
if ([state isEqualToString:@"suspend"]) {
[self saveUnsentActiveTime:0];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self beginBackgroundFocusTask];
NSMutableURLRequest* request = [self.httpClient requestWithMethod:@"POST" path:[NSString stringWithFormat:@"players/%@/on_focus", mUserId]];
NSDictionary* dataDic = [NSDictionary dictionaryWithObjectsAndKeys:
self.app_id, @"app_id",
@"ping", @"state",
timeToPingWith, @"active_time",
getNetType(), @"net_type",
nil];
NSData* postData = [NSJSONSerialization dataWithJSONObject:dataDic options:0 error:nil];
[request setHTTPBody:postData];
// We are already running in a thread so send the request synchronous to keep the thread alive.
[self enqueueRequest:request
onSuccess:nil
onFailure:nil
isSynchronous:true];
[self endBackgroundFocusTask];
});
}
}
- (NSNumber*)getUnsentActiveTime {
if ([unSentActiveTime intValue] == -1) {
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
unSentActiveTime = [defaults objectForKey:@"GT_UNSENT_ACTIVE_TIME"];
if (unSentActiveTime == nil)
unSentActiveTime = 0;
}
return unSentActiveTime;
}
- (void)saveUnsentActiveTime:(NSNumber*)time {
unSentActiveTime = time;
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:time forKey:@"GT_UNSENT_ACTIVE_TIME"];
[defaults synchronize];
}
- (void)sendPurchases:(NSArray*)purchases {
if (mUserId == nil)
return;
NSMutableURLRequest* request = [self.httpClient requestWithMethod:@"POST" path:[NSString stringWithFormat:@"players/%@/on_purchase", mUserId]];
NSDictionary *dataDic = [NSDictionary dictionaryWithObjectsAndKeys:
self.app_id, @"app_id",
purchases, @"purchases",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:dataDic options:0 error:nil];
[request setHTTPBody:postData];
[self enqueueRequest:request
onSuccess:nil
onFailure:nil];
}
- (void)notificationOpened:(NSDictionary*)messageDict isActive:(BOOL)isActive {
BOOL inAppAlert = false;
if (isActive) {
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
inAppAlert = [defaults boolForKey:@"ONESIGNAL_INAPP_ALERT"];
if (inAppAlert) {
self.lastMessageReceived = messageDict;
NSDictionary* additionalData = [self getAdditionalData];
NSString* title = additionalData[@"title"];
if (!title)
title = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"];
id oneSignalAlertViewDelegate = [[OneSignalAlertViewDelegate alloc] initWithMessageDict:messageDict OneSignal:self];
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:title
message:[self getMessageString]
delegate:oneSignalAlertViewDelegate
cancelButtonTitle:@"Close"
otherButtonTitles:nil, nil];
if (additionalData[@"actionButtons"]) {
for(id button in additionalData[@"actionButtons"])
[alertView addButtonWithTitle:button[@"text"]];
}
[alertView show];
return;
}
}
[self handleNotificationOpened:messageDict isActive:isActive];
}
- (void) handleNotificationOpened:(NSDictionary*)messageDict isActive:(BOOL)isActive {
NSString *messageId, *openUrl;
NSDictionary* customDict = [messageDict objectForKey:@"os_data"];
if (customDict == nil)
customDict = [messageDict objectForKey:@"custom"];
messageId = [customDict objectForKey:@"i"];
openUrl = [customDict objectForKey:@"u"];
NSMutableURLRequest* request = [self.httpClient requestWithMethod:@"PUT" path:[NSString stringWithFormat:@"notifications/%@", messageId]];
NSDictionary* dataDic = [NSDictionary dictionaryWithObjectsAndKeys:
self.app_id, @"app_id",
mUserId, @"player_id",
@(YES), @"opened",
nil];
NSData* postData = [NSJSONSerialization dataWithJSONObject:dataDic options:0 error:nil];
[request setHTTPBody:postData];
[self enqueueRequest:request onSuccess:nil onFailure:nil];
if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateActive && openUrl) {
NSURL *url = [NSURL URLWithString:openUrl];
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] openURL:url];
});
}
self.lastMessageReceived = messageDict;
clearBadgeCount(true);
[[UIApplication sharedApplication] cancelAllLocalNotifications];
if (handleNotification)
handleNotification([self getMessageString], [self getAdditionalData], isActive);
}
bool clearBadgeCount(bool fromNotifOpened) {
if (mNotificationTypes == -1 || (mNotificationTypes & NOTIFICATION_TYPE_BADGE) == 0)
return false;
bool wasBadgeSet = [UIApplication sharedApplication].applicationIconBadgeNumber > 0;
if ((!(NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1) && fromNotifOpened) || wasBadgeSet) {
// Clear bages and nofiications from this app.
// Setting to 1 then 0 was needed to clear the notifications on iOS 6 & 7. (Otherwise you can click the notification multiple times.)
// iOS 8+ auto dismisses the notificaiton you tap on so only clear the badge (and notifications [side-effect]) if it was set.
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}
return wasBadgeSet;
}
bool isCapableOfGettingNotificationTypes() {
return [[UIApplication sharedApplication] respondsToSelector:@selector(currentUserNotificationSettings)];
}
int getNotificationTypes() {
if (!mSubscriptionSet)
return -2;
if (mDeviceToken) {
if (isCapableOfGettingNotificationTypes())
return [[UIApplication sharedApplication] currentUserNotificationSettings].types;
else
return NOTIFICATION_TYPE_ALL;
}
return -1;
}
// iOS 8.0+ only
- (void) updateNotificationTypes:(int)notificationTypes {
if (mNotificationTypes == -2)
return;
BOOL changed = (mNotificationTypes != notificationTypes);
mNotificationTypes = notificationTypes;
if (mUserId == nil && mDeviceToken)
[self registerUser];
else if (mDeviceToken)
[self sendNotificationTypesUpdateIsConfirmed:changed];
if (idsAvailableBlockWhenReady && mUserId && getUsableDeviceToken())
idsAvailableBlockWhenReady(mUserId, getUsableDeviceToken());
}
- (NSDictionary*)getAdditionalData {
NSMutableDictionary* additionalData;
NSMutableDictionary* osDataDict = [self.lastMessageReceived objectForKey:@"os_data"];
if (osDataDict) {
additionalData = [self.lastMessageReceived mutableCopy];
if (self.lastMessageReceived[@"os_data"][@"u"])
additionalData[@"launchURL"] = self.lastMessageReceived[@"os_data"][@"u"];
}
else {
additionalData = [self.lastMessageReceived[@"custom"][@"a"] mutableCopy];
if (self.lastMessageReceived[@"custom"][@"u"])
additionalData[@"launchURL"] = self.lastMessageReceived[@"custom"][@"u"];
}
// TODO: Add sound when notification sent with buttons.
if (self.lastMessageReceived[@"aps"][@"sound"] != nil)
additionalData[@"sound"] = self.lastMessageReceived[@"aps"][@"sound"];
if ([self.lastMessageReceived[@"aps"][@"alert"] isKindOfClass:[NSDictionary class]])
additionalData[@"title"] = self.lastMessageReceived[@"aps"][@"alert"][@"title"];
if (osDataDict) {
[additionalData removeObjectForKey:@"aps"];
[additionalData removeObjectForKey:@"os_data"];
}
return additionalData;
}
- (NSString*)getMessageString {
id alertObj = self.lastMessageReceived[@"aps"][@"alert"];
if ([alertObj isKindOfClass:[NSString class]])
return alertObj;
else if ([alertObj isKindOfClass:[NSDictionary class]])
return alertObj[@"body"];
return @"";
}
- (void)postNotification:(NSDictionary*)jsonData {
[self postNotification:jsonData onSuccess:nil onFailure:nil];
}
- (void)postNotification:(NSDictionary*)jsonData onSuccess:(OneSignalResultSuccessBlock)successBlock onFailure:(OneSignalFailureBlock)failureBlock {
NSMutableURLRequest* request = [self.httpClient requestWithMethod:@"POST" path:@"notifications"];
NSMutableDictionary* dataDic = [[NSMutableDictionary alloc] initWithDictionary:jsonData];
dataDic[@"app_id"] = self.app_id;
NSData* postData = [NSJSONSerialization dataWithJSONObject:dataDic options:0 error:nil];
[request setHTTPBody:postData];
[self enqueueRequest:request
onSuccess:^(NSDictionary* results) {
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:results options:0 error:nil];
NSString* jsonResultsString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
onesignal_Log(ONE_S_LL_DEBUG, [NSString stringWithFormat: @"HTTP create notification success %@", jsonResultsString]);
if (successBlock)
successBlock(results);
}
onFailure:^(NSError* error) {
onesignal_Log(ONE_S_LL_ERROR, @"Create notification failed");
onesignal_Log(ONE_S_LL_INFO, [NSString stringWithFormat: @"%@", error]);
if (failureBlock)
failureBlock(error);
}];
}
- (void)postNotificationWithJsonString:(NSString*)jsonString onSuccess:(OneSignalResultSuccessBlock)successBlock onFailure:(OneSignalFailureBlock)failureBlock {
NSError* jsonError;
NSData* data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* jsonData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if (jsonError == nil)
[self postNotification:jsonData onSuccess:successBlock onFailure:failureBlock];
else {
onesignal_Log(ONE_S_LL_WARN,[NSString stringWithFormat: @"postNotification JSON Parse Error: %@", jsonError]);
onesignal_Log(ONE_S_LL_WARN,[NSString stringWithFormat: @"postNotification JSON Parse Error, JSON: %@", jsonString]);
}
}
- (void)enqueueRequest:(NSURLRequest*)request onSuccess:(OneSignalResultSuccessBlock)successBlock onFailure:(OneSignalFailureBlock)failureBlock {
[self enqueueRequest:request onSuccess:successBlock onFailure:failureBlock isSynchronous:false];
}
- (void)enqueueRequest:(NSURLRequest*)request onSuccess:(OneSignalResultSuccessBlock)successBlock onFailure:(OneSignalFailureBlock)failureBlock isSynchronous:(BOOL)isSynchronous {
if (isSynchronous) {
NSURLResponse* response = nil;
NSError* error = nil;
[NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
[self handleJSONNSURLResponse:response data:nil error:error onSuccess:successBlock onFailure:failureBlock];
}
else {
[NSURLConnection
sendAsynchronousRequest:request
queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse* response,
NSData* data,
NSError* error) {
[self handleJSONNSURLResponse:response data:data error:error onSuccess:successBlock onFailure:failureBlock];
}];
}
}
- (void)handleJSONNSURLResponse:(NSURLResponse*) response data:(NSData*) data error:(NSError*) error onSuccess:(OneSignalResultSuccessBlock)successBlock onFailure:(OneSignalFailureBlock)failureBlock {
NSHTTPURLResponse* HTTPResponse = (NSHTTPURLResponse*)response;
NSInteger statusCode = [HTTPResponse statusCode];
NSError* jsonError;
NSMutableDictionary* innerJson;
if (data != nil && [data length] > 0) {
innerJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if (jsonError != nil) {
if (failureBlock != nil)
failureBlock([NSError errorWithDomain:@"OneSignal Error" code:statusCode userInfo:@{@"returned" : jsonError}]);
return;
}
}
if (error == nil && statusCode == 200) {
if (successBlock != nil) {
if (innerJson != nil)
successBlock(innerJson);
else
successBlock(nil);
}
}
else if (failureBlock != nil) {
if (innerJson != nil && error == nil)
failureBlock([NSError errorWithDomain:@"OneSignalError" code:statusCode userInfo:@{@"returned" : innerJson}]);
else if (error != nil)
failureBlock([NSError errorWithDomain:@"OneSignalError" code:statusCode userInfo:@{@"error" : error}]);
else
failureBlock([NSError errorWithDomain:@"OneSignalError" code:statusCode userInfo:nil]);
}
}