-
Notifications
You must be signed in to change notification settings - Fork 3
/
Countly.m
executable file
·756 lines (604 loc) · 29.4 KB
/
Countly.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
// Countly.m
//
// This code is provided under the MIT License.
//
// Please visit www.count.ly for more information.
#import "Countly.h"
#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <CommonCrypto/CommonKeyDerivation.h>
#include <sys/sysctl.h>
#include <libkern/OSAtomic.h>
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#endif
#ifdef COUNTLY_DEBUG
# define COUNTLY_LOG(fmt, ...) NSLog(fmt, ## __VA_ARGS__)
#else
# define COUNTLY_LOG(...)
#endif
#if !__has_feature(objc_arc)
#error Countly must be built with ARC.
#endif
NSString * const CountlyAttributesAPIKey = @"APIKey";
NSString * const CountlyAttributesHost = @"host";
NSString * const CountlyAttributesSessionDurationTrackingEnabled = @"sessionDurationTrackingEnabled";
NSString * const CountlyAttributesEventsSendingViaWWANEnabled = @"eventsSendingViaWWANEnabled";
NSString * const CountlyAttributesSessionDurationUpdateInterval = @"sessionDurationUpdateInterval";
NSString * const CountlyUserDefaultsUUID = @"CountlyUUID";
static NSString *kCountlyVersion = @"1.0";
static NSString * CLYPercentEscapedQueryStringPairMemberFromStringWithEncoding(NSString *string) {
static NSString *const kCLYCharactersToBeEscaped = @":/?&=;+!@#$()~',";
static NSString *const kCLYCharactersToLeaveUnescaped = @"[].";
return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, (__bridge CFStringRef)kCLYCharactersToLeaveUnescaped, (__bridge CFStringRef)kCLYCharactersToBeEscaped, CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
}
static NSData * CLYDigest(NSData *data, unsigned char * (*cc_digest)(const void *, CC_LONG, unsigned char *), CC_LONG digestLength) {
unsigned char md[digestLength];
memset(md, 0, sizeof(md));
cc_digest([data bytes], (CC_LONG)[data length], md);
return [NSData dataWithBytes:md length:sizeof(md)];
}
static NSData * CLYSHA1Hash(NSData *data) {
return CLYDigest(data, CC_SHA1, CC_SHA1_DIGEST_LENGTH);
}
static NSString * CLYHexStringFromData(NSData *data) {
NSUInteger capacity = data.length * 2;
NSMutableString *stringBuffer = [NSMutableString stringWithCapacity:capacity];
const unsigned char *dataBuffer = data.bytes;
NSInteger i;
for (i = 0; i < data.length; ++i) {
[stringBuffer appendFormat:@"%02lx", (long)dataBuffer[i]];
}
return [[NSString stringWithString:stringBuffer]lowercaseString];
}
static NSString * CLYUUIDString() {
CFUUIDRef uid = CFUUIDCreate(kCFAllocatorDefault);
CFStringRef tmpString = CFUUIDCreateString(kCFAllocatorDefault, uid);
CFRelease(uid);
return (__bridge_transfer NSString *)tmpString;
}
static NSString * CLYSystemInfoForKey(char *key) {
size_t size;
sysctlbyname(key, NULL, &size, NULL, 0);
char *answer = malloc(size);
sysctlbyname(key, answer, &size, NULL, 0);
NSString *results = [NSString stringWithCString:answer encoding:NSUTF8StringEncoding];
free(answer);
return results;
}
@interface CLYEvent : NSObject
@property (nonatomic) NSString *key;
@property (nonatomic) NSDictionary *segmentation;
@property (nonatomic) NSUInteger count;
@property (nonatomic) CGFloat sum;
@property (nonatomic) time_t timestamp;
@end
@implementation CLYEvent
@end
static int32_t queueCounter = 0;
@interface CLYEventStack : NSObject {
NSMutableArray *_events;
dispatch_queue_t _queue;
}
@end
@implementation CLYEventStack
- (id)init {
if (self = [super init]) {
_events = [[NSMutableArray alloc] init];
_queue = dispatch_queue_create("com.countly.eventStack", DISPATCH_QUEUE_CONCURRENT);
const char *label = [[NSString stringWithFormat:@"com.countly.eventstack-%i", OSAtomicIncrement32(&queueCounter)] UTF8String];
_queue = dispatch_queue_create(label, DISPATCH_QUEUE_SERIAL);
}
return self;
}
- (void)dealloc {
#if !OS_OBJECT_USE_OBJC
dispatch_release(_queue);
#endif
}
- (NSUInteger)count {
__block NSUInteger retValue;
dispatch_sync(_queue, ^{
retValue = [_events count];
});
return retValue;
}
- (NSArray *)popAllEvents {
__block NSArray *retEvents = nil;
dispatch_sync(_queue, ^{
if (_events.count > 0) {
retEvents = [_events copy];
[_events removeAllObjects];
}
});
COUNTLY_LOG(@"flushAllEvents (%lu events)", (unsigned long)retEvents.count);
return retEvents;
}
- (NSArray *)popEventsMax:(NSUInteger)maxReturnedEvents {
__block NSArray *retEvents = nil;
dispatch_sync(_queue, ^{
if (_events.count > 0) {
if (maxReturnedEvents > _events.count) {
retEvents = [_events copy];
[_events removeAllObjects];
}
else {
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:YES];
NSArray *sortedEvents = [_events sortedArrayUsingDescriptors:@[sortDescriptor]];
retEvents = [sortedEvents subarrayWithRange:NSMakeRange(0, maxReturnedEvents)];
[_events removeObjectsInArray:retEvents];
}
}
});
COUNTLY_LOG(@"flushAllEvents (%lu events)", (unsigned long)retEvents.count);
return retEvents;
}
- (void)pushEvent:(NSString *)key segmentation:(NSDictionary *)segmentation count:(NSUInteger)count sum:(CGFloat)sum {
dispatch_sync(_queue, ^{
__block BOOL identicalEventFound = NO;
[_events enumerateObjectsUsingBlock:^(CLYEvent *event, NSUInteger idx, BOOL *stop) {
if ([event.key
isEqualToString:key] && (!segmentation || [segmentation isEqualToDictionary:event.segmentation])) {
event.count += count;
event.sum += sum;
event.timestamp = (event.timestamp + time(NULL)) / 2;
identicalEventFound = YES;
*stop = identicalEventFound;
}
}];
if (!identicalEventFound) {
CLYEvent *event = [[CLYEvent alloc] init];
event.key = key;
event.segmentation = segmentation;
event.count = count;
event.sum = sum;
event.timestamp = time(NULL);
[_events addObject:event];
}
});
}
@end
typedef NS_ENUM(NSUInteger, CountlySessionState) {
CountlySessionStateStopped,
CountlySessionStateBegan,
CountlySessionStateUpdated,
CountlySessionStatePending
};
typedef enum {
CLYNetworkReachabilityStatusUnknown = -1,
CLYNetworkReachabilityStatusNotReachable = 0,
CLYNetworkReachabilityStatusReachableViaWWAN = 1,
CLYNetworkReachabilityStatusReachableViaWiFi = 2,
} CLYNetworkReachabilityStatus;
typedef SCNetworkReachabilityRef CLYNetworkReachabilityRef;
typedef void (^CLYNetworkReachabilityStatusBlock)(CLYNetworkReachabilityStatus status);
@interface Countly ()
@property (nonatomic) NSTimer *sessionTimer;
@property (nonatomic) NSTimer *eventStackPopTimer;
@property (nonatomic) CFTimeInterval sessionsLastTime;
@property (nonatomic) CLYEventStack *eventStack;
@property (nonatomic) NSString *appKey;
@property (nonatomic) NSString *appHost;
@property (nonatomic) NSString *UUID;
@property (nonatomic) CountlySessionState sessionState;
@property (nonatomic) BOOL applicationInBackgroundState;
@property (nonatomic) NSOperationQueue *httpOperationQueue;
@property (nonatomic) CLYNetworkReachabilityRef networkReachability;
@property (nonatomic) CLYNetworkReachabilityStatus networkReachabilityStatus;
@property (nonatomic, readonly) BOOL isHostReachable;
@property (nonatomic) BOOL shouldTrackSessionDuration;
@property (nonatomic) BOOL shouldSendEventsViaWWAN;
@property (nonatomic) NSTimeInterval sessionDurationUpdateInterval;
@end
@implementation Countly
#pragma mark - Setup and Teardown
+ (instancetype)sharedInstance {
static Countly *_sharedInstance = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedInstance = [[self alloc] init];
});
return _sharedInstance;
}
- (id)init {
if (self = [super init]) {
NSAssert([NSThread isMainThread], @"Countly class should be initialized on the main thread");
self.httpOperationQueue = [[NSOperationQueue alloc] init];
self.httpOperationQueue.maxConcurrentOperationCount = 2;
self.networkReachabilityStatus = CLYNetworkReachabilityStatusUnknown;
self.UUID = [[[NSUserDefaults standardUserDefaults] objectForKey:@"OpenUDID"] objectForKey:@"OpenUDID"]; //legacy UDID
if (!self.UUID) {
self.UUID = [[NSUserDefaults standardUserDefaults] objectForKey:CountlyUserDefaultsUUID];
if (!self.UUID) {
NSString *uudid = CLYUUIDString();
NSData *hash = CLYSHA1Hash([uudid dataUsingEncoding:NSUTF8StringEncoding]);
self.UUID = CLYHexStringFromData(hash);
[[NSUserDefaults standardUserDefaults] setObject:self.UUID forKey:CountlyUserDefaultsUUID];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
self.eventStack = [[CLYEventStack alloc] init];
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterBackgroundNotification:) name:UIApplicationDidEnterBackgroundNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForegroundNotification:) name:UIApplicationWillEnterForegroundNotification object:nil];
#endif
}
return self;
}
- (void)dealloc {
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];
#endif
[self stopMonitoringNetworkReachability];
[self.httpOperationQueue cancelAllOperations];
[self.sessionTimer invalidate];
[self.eventStackPopTimer invalidate];
}
#pragma mark - Public Methods
- (void)startWithAttributes:(NSDictionary *)attributes {
self.sessionsLastTime = CFAbsoluteTimeGetCurrent();
self.appKey = attributes[CountlyAttributesAPIKey];
self.appHost = attributes[CountlyAttributesHost];
self.shouldTrackSessionDuration = (attributes[CountlyAttributesSessionDurationTrackingEnabled]) ? [attributes[CountlyAttributesSessionDurationTrackingEnabled]boolValue] : YES;
self.shouldSendEventsViaWWAN = (attributes[CountlyAttributesEventsSendingViaWWANEnabled]) ? [attributes[CountlyAttributesEventsSendingViaWWANEnabled]boolValue] : YES;
self.sessionDurationUpdateInterval = (attributes[CountlyAttributesSessionDurationUpdateInterval]) ? [attributes[CountlyAttributesSessionDurationUpdateInterval]doubleValue] : 120.;
NSParameterAssert(self.appKey);
NSParameterAssert(self.appHost);
[self startMonitoringNetworkReachability];
}
- (void)recordEvent:(NSString *)key count:(NSUInteger)count {
[self recordEvent:key segmentation:nil count:count sum:0.];
}
- (void)recordEvent:(NSString *)key count:(NSUInteger)count sum:(CGFloat)sum {
[self recordEvent:key segmentation:nil count:count sum:sum];
}
- (void)recordEvent:(NSString *)key segmentation:(NSDictionary *)segmentation count:(NSUInteger)count {
[self recordEvent:key segmentation:segmentation count:count sum:0.];
}
#pragma mark - Session Management
- (void)updateSessionState {
BOOL stopTrackingSession = (!self.shouldTrackSessionDuration && (self.sessionState == CountlySessionStateBegan));
if (self.applicationInBackgroundState || !self.isHostReachable || stopTrackingSession) {
[self.sessionTimer invalidate];
self.sessionTimer = nil;
}
else if (!self.sessionTimer) {
self.sessionTimer = [NSTimer scheduledTimerWithTimeInterval:self.sessionDurationUpdateInterval target:self selector:@selector(sessionTimerFired:) userInfo:nil repeats:YES];
}
if (stopTrackingSession) {
return;
}
if (self.sessionState != CountlySessionStatePending) {
NSURLRequest *request = nil;
void (^callbackBlock)(BOOL, NSError *) = nil;
if (self.sessionState == CountlySessionStateStopped) {
request = [self urlRequestForSessionBegin];
__weak __typeof(self)weakSelf = self;
callbackBlock = ^void(BOOL success, NSError *error) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
strongSelf.sessionState = (success) ? CountlySessionStateBegan : CountlySessionStateStopped;
COUNTLY_LOG(@"updateSessionState (error: %@)",error);
};
}
else if (self.sessionState == CountlySessionStateBegan || self.sessionState == CountlySessionStateUpdated) {
CFTimeInterval lastTime = CFAbsoluteTimeGetCurrent();
CFTimeInterval duration = round(lastTime - self.sessionsLastTime);
self.sessionsLastTime = lastTime;
COUNTLY_LOG(@"session duration: %f sec.", duration);
request = [self urlRequestForSessionUpdateWithDuration:duration];
__weak __typeof(self)weakSelf = self;
callbackBlock = ^void(BOOL success, NSError *error) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
strongSelf.sessionState = (success) ? CountlySessionStateUpdated : CountlySessionStateBegan;
COUNTLY_LOG(@"updateSessionState (error: %@)",error);
};
}
if (request) {
self.sessionState = CountlySessionStatePending;
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
__block UIBackgroundTaskIdentifier backgroundTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^(void) {
if (callbackBlock) callbackBlock(NO, nil);
});
[[UIApplication sharedApplication] endBackgroundTask:backgroundTaskIdentifier];
}];
#endif
[NSURLConnection sendAsynchronousRequest:request queue:self.httpOperationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^(void) {
if (callbackBlock) callbackBlock(!error, error);
});
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
[[UIApplication sharedApplication] endBackgroundTask:backgroundTaskIdentifier];
#endif
}];
}
}
}
- (void)setSessionState:(CountlySessionState)sessionState {
if (sessionState != _sessionState) {
NSAssert([NSThread isMainThread], @"should be called on the main thread");
_sessionState = sessionState;
#ifdef DEBUG
if (_sessionState == CountlySessionStateBegan) {
COUNTLY_LOG(@"session state: began");
}
if (_sessionState == CountlySessionStateUpdated) {
COUNTLY_LOG(@"session state: updated");
}
else if (_sessionState == CountlySessionStatePending) {
COUNTLY_LOG(@"session state: pending");
}
else if (_sessionState == CountlySessionStateStopped) {
COUNTLY_LOG(@"session state: stopped");
}
#endif
}
}
- (void)sessionTimerFired:(NSTimer *)timer {
[self updateSessionState];
}
#pragma mark - Events Management
- (void)recordEvent:(NSString *)key segmentation:(NSDictionary *)segmentation count:(NSUInteger)count sum:(CGFloat)sum {
NSParameterAssert(key);
#ifdef DEBUG
[segmentation.allKeys enumerateObjectsWithOptions:0 usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSAssert([obj isKindOfClass:[NSString class]], @"keys of the segmentation dictionary should be NSString objects");
}];
[segmentation.allValues enumerateObjectsWithOptions:0 usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSAssert([obj isKindOfClass:[NSString class]] || [obj isKindOfClass:[NSNumber class]], @"keys of the segmentation dictionary should be NSString or NSNumber objects");
}];
#endif
[self.eventStack pushEvent:key segmentation:segmentation count:count sum:sum];
dispatch_async(dispatch_get_main_queue(), ^(void) {
if (!self.eventStackPopTimer) {
self.eventStackPopTimer = [NSTimer scheduledTimerWithTimeInterval:5. target:self selector:@selector(eventStackPopTimerFired:) userInfo:nil repeats:NO];
}
});
}
- (void)eventStackPopTimerFired:(NSTimer *)timer {
[self sendPendingEvents];
self.eventStackPopTimer = nil;
}
- (void)sendPendingEvents {
BOOL shouldSendEvents = self.isHostReachable && (self.shouldSendEventsViaWWAN || (!self.shouldSendEventsViaWWAN && self.networkReachabilityStatus != CLYNetworkReachabilityStatusReachableViaWWAN));
if (shouldSendEvents) {
const NSUInteger maxEventsPerRequest = 30;
NSArray *events = [self.eventStack popEventsMax:maxEventsPerRequest];
while (events.count > 0) {
NSMutableArray *mutableArray = [NSMutableArray array];
[events enumerateObjectsWithOptions:0 usingBlock:^(CLYEvent *event, NSUInteger idx, BOOL *stop) {
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionary];
[mutableDictionary setObject:event.key forKey:@"key"];
[mutableDictionary setObject:@(event.count) forKey:@"count"];
[mutableDictionary setObject:@(event.timestamp) forKey:@"timestamp"];
if (event.sum > 0) [mutableDictionary setObject:@(event.sum) forKey:@"sum"];
if (event.segmentation.allKeys.count > 0) [mutableDictionary setObject:event.segmentation forKey:@"segmentation"];
[mutableArray addObject:mutableDictionary];
}];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mutableArray options:0 error:nil];
NSString *jsonEncodedEvents = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *data = [NSString stringWithFormat:@"app_key=%@&device_id=%@×tamp=%ld&events=%@",
CLYPercentEscapedQueryStringPairMemberFromStringWithEncoding(self.appKey),
CLYPercentEscapedQueryStringPairMemberFromStringWithEncoding(self.UUID),
time(NULL),
CLYPercentEscapedQueryStringPairMemberFromStringWithEncoding(jsonEncodedEvents)];
NSString *urlString = [NSString stringWithFormat:@"%@/i?%@", self.appHost, data];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
__block UIBackgroundTaskIdentifier backgroundTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:backgroundTaskIdentifier];
}];
#endif
COUNTLY_LOG(@"sendPendingEvents - start");
[NSURLConnection sendAsynchronousRequest:request queue:self.httpOperationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
COUNTLY_LOG(@"sendPendingEvents - finished (error: %@)",error);
// PS: if an error occurs, the events are lost. Could be improved. Note that we first check that the host is available but it's not enough,
// an error could occur during the request life-time.
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
[[UIApplication sharedApplication] endBackgroundTask:backgroundTaskIdentifier];
#endif
}];
events = [self.eventStack popEventsMax:maxEventsPerRequest];
}
}
}
#pragma mark - Notifications
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
- (void)didEnterBackgroundNotification:(NSNotification *)notification {
COUNTLY_LOG(@"Countly didEnterBackgroundCallBack");
self.applicationInBackgroundState = YES;
[self updateSessionState];
[self sendPendingEvents];
}
- (void)willEnterForegroundNotification:(NSNotification *)notification {
self.applicationInBackgroundState = NO;
CFTimeInterval duration = round(CFAbsoluteTimeGetCurrent() - self.sessionsLastTime);
COUNTLY_LOG(@"Countly willEnterForegroundCallBack (duration in background: %f sec)",duration);
const NSUInteger sleepMaxDurationMinutes = 10;
if (duration < 0 || duration > (60*sleepMaxDurationMinutes)) { // if the wake-up occurs after 10 minutes, we consider it as a new session
COUNTLY_LOG(@"session restarted (wake-up longer than %lu min.)",(unsigned long)sleepMaxDurationMinutes);
self.sessionState = CountlySessionStateStopped;
}
self.sessionsLastTime = CFAbsoluteTimeGetCurrent();
[self updateSessionState];
}
#endif
#pragma mark - Countly API Requests
- (NSURLRequest *)urlRequestForSessionBegin {
NSMutableDictionary *metrics = [NSMutableDictionary dictionary];
// LOCALE
[metrics setObject:[[NSLocale currentLocale] localeIdentifier] forKey:@"_locale"];
// APP VERSION
{
NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
if ([version length] == 0) version = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
[metrics setObject:version forKey:@"_app_version"];
}
// DEVICE
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
[metrics setObject:CLYSystemInfoForKey("hw.machine") forKey:@"_device"];
#else
[metrics setObject:CLYSystemInfoForKey("hw.model") forKey:@"_device"];
#endif
// OS
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
[metrics setObject:@"iOS" forKey:@"_os"];
#else
[metrics setObject:@"MAC" forKey:@"_os"];
#endif
// OS VERSION
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
[metrics setObject:[[UIDevice currentDevice] systemVersion] forKey:@"_os_version"];
#else
{
SInt32 versionMajor = 0, versionMinor = 0, versionBugFix = 0;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
Gestalt(gestaltSystemVersionMajor, &versionMajor);
Gestalt(gestaltSystemVersionMinor, &versionMinor);
Gestalt(gestaltSystemVersionBugFix, &versionBugFix);
#pragma clang diagnostic pop
NSString *version = [NSString stringWithFormat:@"%d.%d.%d", versionMajor, versionMinor, versionBugFix];
[metrics setObject:version forKey:@"_os_version"];
}
#endif
// RESOLUTION
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
{
CGRect bounds = [[UIScreen mainScreen] bounds];
CGFloat scale = [[UIScreen mainScreen] scale];
CGSize res = CGSizeMake(bounds.size.width * scale, bounds.size.height * scale);
NSString *resolution = [NSString stringWithFormat:@"%gx%g", res.width, res.height];
[metrics setObject:resolution forKey:@"_resolution"];
}
#else
{
NSRect frame = [[NSScreen mainScreen] frame];
NSRect res = [[NSScreen mainScreen] convertRectToBacking:frame];
NSString *resolution = [NSString stringWithFormat:@"%gx%g", res.size.width, res.size.height];
[metrics setObject:resolution forKey:@"_resolution"];
}
#endif
// CARRIER
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
{
CTTelephonyNetworkInfo *netinfo = [[CTTelephonyNetworkInfo alloc] init];
NSString *carrierName = [[netinfo subscriberCellularProvider] carrierName];
if (carrierName) [metrics setObject:carrierName forKey:@"_carrier"];
}
#endif
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:metrics options:0 error:nil];
NSString *jsonEncodedMetrics = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *data = [NSString stringWithFormat:@"app_key=%@&device_id=%@×tamp=%ld&sdk_version=%@&begin_session=1&metrics=%@",
CLYPercentEscapedQueryStringPairMemberFromStringWithEncoding(self.appKey),
CLYPercentEscapedQueryStringPairMemberFromStringWithEncoding(self.UUID),
time(NULL),
kCountlyVersion,
CLYPercentEscapedQueryStringPairMemberFromStringWithEncoding(jsonEncodedMetrics)];
NSString *urlString = [NSString stringWithFormat:@"%@/i?%@", self.appHost, data];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
return request;
}
- (NSURLRequest *)urlRequestForSessionUpdateWithDuration:(CFTimeInterval)duration {
NSString *data = [NSString stringWithFormat:@"app_key=%@&device_id=%@×tamp=%ld&session_duration=%f",
CLYPercentEscapedQueryStringPairMemberFromStringWithEncoding(self.appKey),
CLYPercentEscapedQueryStringPairMemberFromStringWithEncoding(self.UUID),
time(NULL),
round(duration)];
NSString *urlString = [NSString stringWithFormat:@"%@/i?%@", self.appHost, data];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
return request;
}
#pragma mark - Network Reachability
- (void)setNetworkReachabilityStatus:(CLYNetworkReachabilityStatus)networkReachabilityStatus {
if (networkReachabilityStatus != _networkReachabilityStatus) {
_networkReachabilityStatus = networkReachabilityStatus;
#ifdef DEBUG
if (_networkReachabilityStatus == CLYNetworkReachabilityStatusUnknown) {
COUNTLY_LOG(@"reachability changed: unknown");
}
if (_networkReachabilityStatus == CLYNetworkReachabilityStatusNotReachable) {
COUNTLY_LOG(@"reachability changed: not reachable");
}
else {
COUNTLY_LOG(@"reachability changed: reachable");
}
#endif
if (_networkReachabilityStatus != CLYNetworkReachabilityStatusUnknown) {
[self updateSessionState];
[self sendPendingEvents];
}
}
}
- (BOOL)isHostReachable {
BOOL isHostReachable = (self.networkReachabilityStatus == CLYNetworkReachabilityStatusReachableViaWWAN || self.networkReachabilityStatus == CLYNetworkReachabilityStatusReachableViaWiFi);
return isHostReachable;
}
#pragma mark Reachability
// based on the code of AFNetworking (https://github.com/AFNetworking/AFNetworking)
static CLYNetworkReachabilityStatus CLYNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) {
BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0);
BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0);
BOOL isNetworkReachable = (isReachable && !needsConnection);
CLYNetworkReachabilityStatus status = CLYNetworkReachabilityStatusUnknown;
if (isNetworkReachable == NO) {
status = CLYNetworkReachabilityStatusNotReachable;
}
#if TARGET_OS_IPHONE
else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) {
status = CLYNetworkReachabilityStatusReachableViaWWAN;
}
#endif
else {
status = CLYNetworkReachabilityStatusReachableViaWiFi;
}
return status;
}
static void CLYNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) {
CLYNetworkReachabilityStatus status = CLYNetworkReachabilityStatusForFlags(flags);
CLYNetworkReachabilityStatusBlock block = (__bridge CLYNetworkReachabilityStatusBlock)info;
if (block) {
block(status);
}
}
static const void * CLYNetworkReachabilityRetainCallback(const void *info) {
return (__bridge_retained const void *)([(__bridge CLYNetworkReachabilityStatusBlock)info copy]);
}
static void CLYNetworkReachabilityReleaseCallback(const void *info) {
if (info) {
CFRelease(info);
}
}
- (void)startMonitoringNetworkReachability {
[self stopMonitoringNetworkReachability];
if (!self.appHost) {
return;
}
self.networkReachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [[[NSURL URLWithString:self.appHost] host] UTF8String]);
if (!self.networkReachability) {
return;
}
__weak __typeof(&*self)weakSelf = self;
CLYNetworkReachabilityStatusBlock callback = ^(CLYNetworkReachabilityStatus status) {
__strong __typeof(&*weakSelf)strongSelf = weakSelf;
dispatch_async(dispatch_get_main_queue(), ^{
strongSelf.networkReachabilityStatus = status;
});
};
SCNetworkReachabilityContext context = {0, (__bridge void *)callback, CLYNetworkReachabilityRetainCallback, CLYNetworkReachabilityReleaseCallback, NULL};
SCNetworkReachabilitySetCallback(self.networkReachability, CLYNetworkReachabilityCallback, &context);
SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), (CFStringRef)NSRunLoopCommonModes);
SCNetworkReachabilityFlags flags;
SCNetworkReachabilityGetFlags(self.networkReachability, &flags);
}
- (void)stopMonitoringNetworkReachability {
if (_networkReachability) {
SCNetworkReachabilityUnscheduleFromRunLoop(_networkReachability, CFRunLoopGetMain(), (CFStringRef)NSRunLoopCommonModes);
CFRelease(_networkReachability);
_networkReachability = NULL;
}
}
@end