summaryrefslogtreecommitdiff
path: root/platform/ios/MGLMapboxEvents.m
blob: 9fcfc71536901ab8c5198253f6454a592b94d007 (plain)
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
#import "MGLMapboxEvents_Private.h"

#import <UIKit/UIKit.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import <CoreLocation/CoreLocation.h>

#import "MGLAccountManager.h"
#import "NSProcessInfo+MGLAdditions.h"
#import "NSBundle+MGLAdditions.h"
#import "NSException+MGLAdditions.h"

#include <sys/sysctl.h>

static NSString *const MGLMapboxEventsUserAgent = @"MapboxEventsiOS/1.0";
static NSString *const MGLMapboxEventsAPIBase = @"https://api.tiles.mapbox.com";

NSString *const MGLEventTypeMapLoad = @"map.load";
NSString *const MGLEventTypeMapTap = @"map.click";
NSString *const MGLEventTypeMapDragEnd = @"map.dragend";
NSString *const MGLEventTypeLocation = @"location";
NSString *const MGLEventTypeVisit = @"visit";

NSString *const MGLEventKeyLatitude = @"lat";
NSString *const MGLEventKeyLongitude = @"lng";
NSString *const MGLEventKeyZoomLevel = @"zoom";
NSString *const MGLEventKeySpeed = @"speed";
NSString *const MGLEventKeyCourse = @"course";
NSString *const MGLEventKeyAltitude = @"altitude";
NSString *const MGLEventKeyHorizontalAccuracy = @"horizontalAccuracy";
NSString *const MGLEventKeyVerticalAccuracy = @"verticalAccuracy";
NSString *const MGLEventKeyPushEnabled = @"enabled.push";
NSString *const MGLEventKeyEmailEnabled = @"enabled.email";
NSString *const MGLEventKeyGestureID = @"gesture";
NSString *const MGLEventKeyArrivalDate = @"arrivalDate";
NSString *const MGLEventKeyDepartureDate = @"departureDate";

NSString *const MGLEventGestureSingleTap = @"SingleTap";
NSString *const MGLEventGestureDoubleTap = @"DoubleTap";
NSString *const MGLEventGestureTwoFingerSingleTap = @"TwoFingerTap";
NSString *const MGLEventGestureQuickZoom = @"QuickZoom";
NSString *const MGLEventGesturePanStart = @"Pan";
NSString *const MGLEventGesturePinchStart = @"Pinch";
NSString *const MGLEventGestureRotateStart = @"Rotation";

const NSUInteger MGLMaximumEventsPerFlush = 20;
const NSTimeInterval MGLFlushInterval = 60;

@interface MGLMapboxEventsData : NSObject

// All of the following properties are written to only from
// the main thread, but can be read on any thread.
//
@property (atomic) NSString *instanceID;
@property (atomic) NSString *advertiserId;
@property (atomic) NSString *vendorId;
@property (atomic) NSString *model;
@property (atomic) NSString *iOSVersion;
@property (atomic) NSString *carrier;
@property (atomic) CGFloat scale;

@end

@implementation MGLMapboxEventsData

- (instancetype)init {
    if (self = [super init]) {
        _instanceID = [[NSUUID UUID] UUIDString];
        
        // Dynamic detection of ASIdentifierManager from Mixpanel
        // https://github.com/mixpanel/mixpanel-iphone/blob/master/LICENSE
        _advertiserId = @"";
        Class ASIdentifierManagerClass = NSClassFromString(@"ASIdentifierManager");
        if (ASIdentifierManagerClass) {
            SEL sharedManagerSelector = NSSelectorFromString(@"sharedManager");
            id sharedManager = ((id (*)(id, SEL))[ASIdentifierManagerClass methodForSelector:sharedManagerSelector])(ASIdentifierManagerClass, sharedManagerSelector);
            // Add check here
            SEL isAdvertisingTrackingEnabledSelector = NSSelectorFromString(@"isAdvertisingTrackingEnabled");
            BOOL trackingEnabled = ((BOOL (*)(id, SEL))[sharedManager methodForSelector:isAdvertisingTrackingEnabledSelector])(sharedManager, isAdvertisingTrackingEnabledSelector);
            if (trackingEnabled) {
                SEL advertisingIdentifierSelector = NSSelectorFromString(@"advertisingIdentifier");
                NSUUID *uuid = ((NSUUID* (*)(id, SEL))[sharedManager methodForSelector:advertisingIdentifierSelector])(sharedManager, advertisingIdentifierSelector);
                _advertiserId = [uuid UUIDString];
            }
        }
        _vendorId = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        
        _model = [self sysInfoByName:"hw.machine"];
        _iOSVersion = [NSString stringWithFormat:@"%@ %@", [UIDevice currentDevice].systemName, [UIDevice currentDevice].systemVersion];
        if ([UIScreen instancesRespondToSelector:@selector(nativeScale)]) {
            _scale = [UIScreen mainScreen].nativeScale;
        } else {
            _scale = [UIScreen mainScreen].scale;
        }
        CTCarrier *carrierVendor = [[[CTTelephonyNetworkInfo alloc] init] subscriberCellularProvider];
        _carrier = [carrierVendor carrierName];
    }
    return self;
}

// Can be called from any thread.
//
- (NSString *)sysInfoByName:(char *)typeSpecifier
{
    size_t size;
    sysctlbyname(typeSpecifier, NULL, &size, NULL, 0);
    
    char *answer = malloc(size);
    sysctlbyname(typeSpecifier, answer, &size, NULL, 0);
    
    NSString *results = [NSString stringWithCString:answer encoding: NSUTF8StringEncoding];
    
    free(answer);
    return results;
}

@end

//
// Threadsafety conventions:
//
// All variables accessed from more than one thread are
// designated `atomic` and accessed through dot syntax. The
// main thread uses underscore syntax during the
// initialization of the variable.
//
// All variables accessed outside of initialization and
// from within a single thread use underscore syntax.
//
// All captures of `self` from within asynchronous
// dispatches will use a `strongSelf` to avoid cyclical
// strong references.
//

@interface MGLMapboxEvents () <CLLocationManagerDelegate>

// All of the following properties are written to only from
// the main thread, but can be read on any thread.
//
@property (atomic) MGLMapboxEventsData *data;
@property (atomic) NSString *appBundleId;
@property (atomic) NSString *appName;
@property (atomic) NSString *appVersion;
@property (atomic) NSString *appBuildNumber;
@property (atomic) NSDateFormatter *rfc3339DateFormatter;
@property (atomic) NSURLSession *session;
@property (atomic) NSData *digicertCert;
@property (atomic) NSData *geoTrustCert;

// Main thread only
@property (nonatomic) CLLocationManager *locationManager;

// The paused state tracker is only ever accessed from the main thread.
//
@property (nonatomic, getter=isPaused) BOOL paused;

// The timer is only ever accessed from the main thread.
//
@property (nonatomic) NSTimer *timer;

// This is an array of events to push. All access to it will be
// from our own serial queue.
//
@property (nonatomic) NSMutableArray *eventQueue;

// This is a custom serial queue for accessing the event queue.
//
@property (nonatomic) dispatch_queue_t serialQueue;

@end

@implementation MGLMapboxEvents {
    id _userDefaultsObserver;
}

+ (void)initialize {
    if (self == [MGLMapboxEvents class]) {
        [[NSUserDefaults standardUserDefaults] registerDefaults:@{
             @"MGLMapboxAccountType": @0,
             @"MGLMapboxMetricsEnabled": @YES,
         }];
    }
}

+ (BOOL)isEnabled {
    return ([[NSUserDefaults standardUserDefaults] boolForKey:@"MGLMapboxMetricsEnabled"] &&
            [[NSUserDefaults standardUserDefaults] integerForKey:@"MGLMapboxAccountType"] == 0);
}

// Must be called from the main thread. Only called internally.
//
- (instancetype) init {
    MGLAssertIsMainThread();

    self = [super init];
    if (self) {
        if (! [MGLAccountManager mapboxMetricsEnabledSettingShownInApp]) {
            // Opt Out is not configured in UI, so check for Settings.bundle
            // Put Settings bundle into memory
            id defaultEnabledValue;
            NSString *appSettingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"];

            if (appSettingsBundle) {
                // Dynamic Settings.bundle loading based on:
                // http://stackoverflow.com/questions/510216/can-you-make-the-settings-in-settings-bundle-default-even-if-you-dont-open-the
                NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[appSettingsBundle stringByAppendingPathComponent:@"Root.plist"]];
                NSArray *preferences = settings[@"PreferenceSpecifiers"];
                for (NSDictionary *prefSpecification in preferences) {
                    if ([prefSpecification[@"Key"] isEqualToString:@"MGLMapboxMetricsEnabled"]) {
                        defaultEnabledValue = prefSpecification[@"DefaultValue"];
                    }
                }
            }

            NSAssert(defaultEnabledValue, @"End users must be able to opt out of Metrics in your app, either inside Settings (via Settings.bundle) or inside this app. If you implement the opt-out control inside this app, disable this assertion by setting [MGLAccountManager setMapboxMetricsEnabledSettingShownInApp:YES] before the app initializes any Mapbox GL classes.");
            [[NSUserDefaults standardUserDefaults] registerDefaults:@{
                 @"MGLMapboxMetricsEnabled": defaultEnabledValue,
             }];
        }

        _appBundleId = [[NSBundle mainBundle] bundleIdentifier];
        _appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
        _appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
        _appBuildNumber = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
        
        NSString *uniqueID = [[NSProcessInfo processInfo] globallyUniqueString];
        _serialQueue = dispatch_queue_create([[NSString stringWithFormat:@"%@.%@.events.serial", _appBundleId, uniqueID] UTF8String], DISPATCH_QUEUE_SERIAL);

        // Configure Events Infrastructure
        // ===============================

        _paused = YES;
        [self resumeMetricsCollection];
        NSBundle *resourceBundle = [NSBundle bundleWithPath:[NSBundle mgl_resourceBundlePath]];

        // Load Local Copy of Server's Public Key
        NSString *cerPath = nil;
        cerPath = [resourceBundle pathForResource:@"api_mapbox_com-geotrust" ofType:@"der"];
        if (cerPath != nil) {
            _geoTrustCert = [NSData dataWithContentsOfFile:cerPath];
        }

        cerPath = [resourceBundle pathForResource:@"api_mapbox_com-digicert" ofType:@"der"];
        if (cerPath != nil) {
            _digicertCert = [NSData dataWithContentsOfFile:cerPath];
        }

        // Events Control
        _eventQueue = [[NSMutableArray alloc] init];
        
        // Setup Date Format
        _rfc3339DateFormatter = [[NSDateFormatter alloc] init];
        NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
        
        [_rfc3339DateFormatter setLocale:enUSPOSIXLocale];
        [_rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ssZ"];
        // Clear Any System TimeZone Cache
        [NSTimeZone resetSystemTimeZone];
        [_rfc3339DateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
        
        // Enable Battery Monitoring
        [UIDevice currentDevice].batteryMonitoringEnabled = YES;
        
        __weak MGLMapboxEvents *weakSelf = self;
        _userDefaultsObserver = [[NSNotificationCenter defaultCenter] addObserverForName:NSUserDefaultsDidChangeNotification
                                                                                  object:nil
                                                                                   queue:[NSOperationQueue mainQueue]
                                                                              usingBlock:
         ^(NSNotification *notification) {
             MGLMapboxEvents *strongSelf = weakSelf;
             [strongSelf validate];
         }];
    }
    return self;
}

// Can be called from any thread. Called implicitly from any
// public class convenience methods. May return nil if this feature is disabled.
//
+ (instancetype)sharedManager {
    if (NSProcessInfo.processInfo.mgl_isInterfaceBuilderDesignablesAgent) {
        return;
    }
    static dispatch_once_t onceToken;
    static MGLMapboxEvents *_sharedManager;
    void (^setupBlock)() = ^{
        dispatch_once(&onceToken, ^{
            _sharedManager = [[self alloc] init];
        });
    };
    if ( ! [[NSThread currentThread] isMainThread]) {
        dispatch_sync(dispatch_get_main_queue(), ^{
            setupBlock();
        });
    }
    else {
        setupBlock();
    }
    return _sharedManager;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:_userDefaultsObserver];
    [self pauseMetricsCollection];
}

+ (void)validate {
    [[MGLMapboxEvents sharedManager] validate];
}

- (void)validate {
    MGLAssertIsMainThread();
    BOOL enabledInSettings = [[self class] isEnabled];
    if (self.paused && enabledInSettings) {
        [self resumeMetricsCollection];
    } else if (!self.paused && !enabledInSettings) {
        [self pauseMetricsCollection];
    }
    
    [self validateUpdatingLocation];
}

- (void)validateUpdatingLocation {
    MGLAssertIsMainThread();
    if (self.paused) {
        [self stopUpdatingLocation];
    } else {
        CLAuthorizationStatus authStatus = [CLLocationManager authorizationStatus];
        if (authStatus == kCLAuthorizationStatusDenied ||
            authStatus == kCLAuthorizationStatusRestricted) {
            [self stopUpdatingLocation];
        } else if (authStatus == kCLAuthorizationStatusAuthorized ||
                   authStatus == kCLAuthorizationStatusAuthorizedWhenInUse) {
            [self startUpdatingLocation];
        }
    }
}

+ (void)pauseMetricsCollection {
    [[MGLMapboxEvents sharedManager] pauseMetricsCollection];
}

// Must be called from the main thread.
//
- (void)pauseMetricsCollection {
    MGLAssertIsMainThread();
    if (self.paused) {
        return;
    }
    self.paused = YES;
    [_timer invalidate];
    _timer = nil;
    [_eventQueue removeAllObjects];
    _data = nil;
    [_session invalidateAndCancel];
    _session = nil;
    
    [self validateUpdatingLocation];
}

- (void)stopUpdatingLocation {
    [_locationManager stopUpdatingLocation];
    
    // -[CLLocationManager stopMonitoringVisits] is only available in iOS 8+.
    if ([_locationManager respondsToSelector:@selector(stopMonitoringVisits)]) {
        [_locationManager stopMonitoringVisits];
    }
    
    _locationManager = nil;
}

+ (void)resumeMetricsCollection {
    [[MGLMapboxEvents sharedManager] resumeMetricsCollection];
}

// Must be called from the main thread.
//
- (void)resumeMetricsCollection {
    MGLAssertIsMainThread();
    if (!self.paused || ![[self class] isEnabled]) {
        return;
    }
    self.paused = NO;
    _data = [[MGLMapboxEventsData alloc] init];
    _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
    
    [self validateUpdatingLocation];
}

- (void)startUpdatingLocation {
    MGLAssertIsMainThread();
    if (_locationManager || _paused) {
        NSAssert(!(_locationManager && _paused),
                 @"MGLMapboxEvents should not have a CLLocationManager while paused.");
        return;
    }
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
    _locationManager.distanceFilter = 10;
    _locationManager.delegate = self;
    
    [_locationManager startUpdatingLocation];
    
    // -[CLLocationManager startMonitoringVisits] is only available in iOS 8+.
    if ([_locationManager respondsToSelector:@selector(startMonitoringVisits)]) {
        [_locationManager startMonitoringVisits];
    }
}

// Can be called from any thread. Can be called rapidly from
// the UI thread, so performance is paramount.
//
+ (void) pushEvent:(NSString *)event withAttributes:(NSDictionary *)attributeDictionary {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        [[MGLMapboxEvents sharedManager] pushEvent:event withAttributes:attributeDictionary];
    });
}

// Can be called from any thread. Called implicitly from public
// use of +pushEvent:withAttributes:.
//
- (void) pushEvent:(NSString *)event withAttributes:(NSDictionary *)attributeDictionary {
    __weak MGLMapboxEvents *weakSelf = self;

    dispatch_async(_serialQueue, ^{
        MGLMapboxEvents *strongSelf = weakSelf;
        if ( ! strongSelf) return;
        
        // Metrics Collection Has Been Paused
        if (_paused) {
            return;
        }
        
        if (!event) return;

        NSMutableDictionary *evt = [[NSMutableDictionary alloc] initWithDictionary:attributeDictionary];
        // mapbox-events stock attributes
        [evt setObject:event forKey:@"event"];
        [evt setObject:@(1) forKey:@"version"];
        [evt setObject:[strongSelf.rfc3339DateFormatter stringFromDate:[NSDate date]] forKey:@"created"];
        [evt setObject:strongSelf.data.instanceID forKey:@"instance"];
        [evt setObject:strongSelf.data.advertiserId forKey:@"advertiserId"];
        [evt setObject:strongSelf.data.vendorId forKey:@"vendorId"];
        [evt setObject:strongSelf.appBundleId forKeyedSubscript:@"appBundleId"];
        
        // mapbox-events-ios stock attributes
        [evt setValue:strongSelf.data.model forKey:@"model"];
        [evt setValue:strongSelf.data.iOSVersion forKey:@"operatingSystem"];
        [evt setValue:[strongSelf deviceOrientation] forKey:@"orientation"];
        [evt setValue:@((int)(100 * [UIDevice currentDevice].batteryLevel)) forKey:@"batteryLevel"];
        [evt setValue:@(strongSelf.data.scale) forKey:@"resolution"];
        [evt setValue:strongSelf.data.carrier forKey:@"carrier"];
        
        NSString *cell = [strongSelf currentCellularNetworkConnectionType];
        if (cell) {
            [evt setValue:cell forKey:@"cellularNetworkType"];
        } else {
            [evt setObject:[NSNull null] forKey:@"cellularNetworkType"];
        }
        
        NSString *wifi = [strongSelf wifiNetworkName];
        if (wifi) {
            [evt setValue:wifi forKey:@"wifi"];
        } else {
            [evt setObject:[NSNull null] forKey:@"wifi"];
        }
        
        [evt setValue:@([strongSelf contentSizeScale]) forKey:@"accessibilityFontScale"];

        // Make Immutable Version
        NSDictionary *finalEvent = [NSDictionary dictionaryWithDictionary:evt];
        
        // Put On The Queue
        [_eventQueue addObject:finalEvent];
        
        // Has Flush Limit Been Reached?
        if (_eventQueue.count >= MGLMaximumEventsPerFlush) {
            [strongSelf flush];
        } else if (_eventQueue.count ==  1) {
            // If this is first new event on queue start timer,
            [strongSelf startTimer];
        }
    });
}

// Can be called from any thread.
//
+ (void) flush {
    [[MGLMapboxEvents sharedManager] flush];
}

// Can be called from any thread.
//
- (void) flush {
    if ([MGLAccountManager accessToken] == nil) return;

    __weak MGLMapboxEvents *weakSelf = self;

    dispatch_async(_serialQueue, ^{
        MGLMapboxEvents *strongSelf = weakSelf;
        if ( ! strongSelf || [_eventQueue count] == 0) return;

        // Make an immutable copy
        NSArray *events = [NSArray arrayWithArray:_eventQueue];

        // Update Queue to remove events sent to server
        [_eventQueue removeAllObjects];

        // Send Array of Events to Server
        [strongSelf postEvents:events];

        // Cancel Any Timer That May Running
        if (strongSelf.timer) {
            [strongSelf.timer invalidate];
            strongSelf.timer = nil;
        }
    });
}

// Can be called from any thread. Called implicitly from public
// use of +flush. Posts an async network request to upload metrics.
//
- (void) postEvents:(NSArray *)events {
    __weak MGLMapboxEvents *weakSelf = self;

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        MGLMapboxEvents *strongSelf = weakSelf;
        if (!strongSelf) return;

        // Setup URL Request
        NSString *url = [NSString stringWithFormat:@"%@/events/v1?access_token=%@", MGLMapboxEventsAPIBase, [MGLAccountManager accessToken]];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
        [request setValue:strongSelf.userAgent forHTTPHeaderField:@"User-Agent"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPMethod:@"POST"];
        
        // Convert Array of Dictionaries to JSON
        if ([NSJSONSerialization isValidJSONObject:events]) {
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:events options:NSJSONWritingPrettyPrinted error:nil];
            [request setHTTPBody:jsonData];

            // Send non blocking HTTP Request to server
            NSURLSessionDataTask *task = [_session dataTaskWithRequest:request completionHandler: nil];
            [task resume];
        }
    });
}

// Can be called from any thread.
//
- (void) startTimer {
    void (^timerBlock)() = ^{
        // Stop Timer if it already exists
        [_timer invalidate];

        // Start New Timer
        _timer = [NSTimer scheduledTimerWithTimeInterval:MGLFlushInterval
                                                  target:self
                                                selector:@selector(flush)
                                                userInfo:nil
                                                 repeats:YES];
    };

    if ( ! [[NSThread currentThread] isMainThread]) {
        dispatch_sync(dispatch_get_main_queue(), ^{
            timerBlock();
        });
    } else {
        timerBlock();
    }
}

// Can be called from any thread.
//
- (NSString *) userAgent {
    return [NSString stringWithFormat:@"%@/%@/%@ %@", self.appName, self.appVersion, self.appBuildNumber, MGLMapboxEventsUserAgent];
}

// Can be called from any thread.
//
- (NSString *) deviceOrientation {
    __block NSString *result;

    NSString *(^deviceOrientationBlock)(void) = ^{
        switch ([UIDevice currentDevice].orientation) {
            case UIDeviceOrientationUnknown:
                result = @"Unknown";
                break;
            case UIDeviceOrientationPortrait:
                result = @"Portrait";
                break;
            case UIDeviceOrientationPortraitUpsideDown:
                result = @"PortraitUpsideDown";
                break;
            case UIDeviceOrientationLandscapeLeft:
                result = @"LandscapeLeft";
                break;
            case UIDeviceOrientationLandscapeRight:
                result = @"LandscapeRight";
                break;
            case UIDeviceOrientationFaceUp:
                result = @"FaceUp";
                break;
            case UIDeviceOrientationFaceDown:
                result = @"FaceDown";
                break;
            default:
                result = @"Default - Unknown";
                break;
        }

        return result;
    };

    if ( ! [[NSThread currentThread] isMainThread]) {
        dispatch_sync(dispatch_get_main_queue(), ^{
            result = deviceOrientationBlock();
        });
    } else {
        result = deviceOrientationBlock();
    }

    return result;
}

// Can be called from any thread.
//
- (NSInteger) contentSizeScale {
    __block NSInteger result = -9999;

    NSInteger (^contentSizeScaleBlock)(void) = ^{
        NSString *sc = [UIApplication sharedApplication].preferredContentSizeCategory;

        if ([sc isEqualToString:UIContentSizeCategoryExtraSmall]) {
            result = -3;
        } else if ([sc isEqualToString:UIContentSizeCategorySmall]) {
            result = -2;
        } else if ([sc isEqualToString:UIContentSizeCategoryMedium]) {
            result = -1;
        } else if ([sc isEqualToString:UIContentSizeCategoryLarge]) {
            result = 0;
        } else if ([sc isEqualToString:UIContentSizeCategoryExtraLarge]) {
            result = 1;
        } else if ([sc isEqualToString:UIContentSizeCategoryExtraExtraLarge]) {
            result = 2;
        } else if ([sc isEqualToString:UIContentSizeCategoryExtraExtraExtraLarge]) {
            result = 3;
        } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityMedium]) {
            result = -11;
        } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityLarge]) {
            result = 10;
        } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityExtraLarge]) {
            result = 11;
        } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraLarge]) {
            result = 12;
        } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraExtraLarge]) {
            result = 13;
        }

        return result;
    };

    if ( ! [[NSThread currentThread] isMainThread]) {
        dispatch_sync(dispatch_get_main_queue(), ^{
            result = contentSizeScaleBlock();
        });
    } else {
        result = contentSizeScaleBlock();
    }

    return result;
}

// Can be called from any thread.
//
- (NSString *) wifiNetworkName {
    
    NSString *ssid = nil;
    CFArrayRef interfaces = CNCopySupportedInterfaces();
    if (interfaces) {
        NSDictionary *info = CFBridgingRelease(CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(interfaces, 0)));
        if (info) {
            ssid = info[@"SSID"];
        }
        CFRelease(interfaces);
    }
    
    return ssid;
}

// Can be called from any thread.
//
- (NSString *) currentCellularNetworkConnectionType {
    CTTelephonyNetworkInfo *telephonyInfo = [[CTTelephonyNetworkInfo alloc] init];
    NSString *radioTech = telephonyInfo.currentRadioAccessTechnology;
    
    if (radioTech == nil) {
        return nil;
    } else if ([radioTech isEqualToString:CTRadioAccessTechnologyGPRS]) {
        return @"GPRS";
    } else if ([radioTech isEqualToString:CTRadioAccessTechnologyEdge]) {
        return @"EDGE";
    } else if ([radioTech isEqualToString:CTRadioAccessTechnologyWCDMA]) {
        return @"WCDMA";
    } else if ([radioTech isEqualToString:CTRadioAccessTechnologyHSDPA]) {
        return @"HSDPA";
    } else if ([radioTech isEqualToString:CTRadioAccessTechnologyHSUPA]) {
        return @"HSUPA";
    } else if ([radioTech isEqualToString:CTRadioAccessTechnologyCDMA1x]) {
        return @"CDMA1x";
    } else if ([radioTech isEqualToString:CTRadioAccessTechnologyCDMAEVDORev0]) {
        return @"CDMAEVDORev0";
    } else if ([radioTech isEqualToString:CTRadioAccessTechnologyCDMAEVDORevA]) {
        return @"CDMAEVDORevA";
    } else if ([radioTech isEqualToString:CTRadioAccessTechnologyCDMAEVDORevB]) {
        return @"CDMAEVDORevB";
    } else if ([radioTech isEqualToString:CTRadioAccessTechnologyeHRPD]) {
        return @"HRPD";
    } else if ([radioTech isEqualToString:CTRadioAccessTechnologyLTE]) {
        return @"LTE";
    } else {
        return @"Unknown";
    }
}

// Can be called from any thread.
//
+ (BOOL) checkPushEnabled {
    BOOL (^pushCheckBlock)(void) = ^{
        BOOL blockResult;
        if ([[UIApplication sharedApplication] respondsToSelector:@selector(isRegisteredForRemoteNotifications)]) {
            // iOS 8+
            blockResult = [[UIApplication sharedApplication] isRegisteredForRemoteNotifications];
        } else {
            // iOS 7
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
            UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
            blockResult = (types == UIRemoteNotificationTypeNone) ? NO : YES;
#pragma clang diagnostic pop
        }
        return blockResult;
    };

    __block BOOL result;

    if ( ! [[NSThread currentThread] isMainThread]) {
        dispatch_sync(dispatch_get_main_queue(), ^{
            result = pushCheckBlock();
        });
    } else {
        result = pushCheckBlock();
    }

    return result;
}

#pragma mark CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    //  Iterate through locations to pass all data
    for (CLLocation *loc in locations) {
        [MGLMapboxEvents pushEvent:MGLEventTypeLocation withAttributes:@{
            MGLEventKeyLatitude: @(loc.coordinate.latitude),
            MGLEventKeyLongitude: @(loc.coordinate.longitude),
            MGLEventKeySpeed: @(loc.speed),
            MGLEventKeyCourse: @(loc.course),
            MGLEventKeyAltitude: @(loc.altitude),
            MGLEventKeyHorizontalAccuracy: @(loc.horizontalAccuracy),
            MGLEventKeyVerticalAccuracy: @(loc.verticalAccuracy)
        }];
    }
}

- (void)locationManager:(CLLocationManager *)manager didVisit:(CLVisit *)visit {
    [MGLMapboxEvents pushEvent:MGLEventTypeVisit withAttributes:@{
        MGLEventKeyLatitude: @(visit.coordinate.latitude),
        MGLEventKeyLongitude: @(visit.coordinate.longitude),
        MGLEventKeyHorizontalAccuracy: @(visit.horizontalAccuracy),
        MGLEventKeyArrivalDate: [[NSDate distantPast] isEqualToDate:visit.arrivalDate] ? [NSNull null] : [_rfc3339DateFormatter stringFromDate:visit.arrivalDate],
        MGLEventKeyDepartureDate: [[NSDate distantFuture] isEqualToDate:visit.departureDate] ? [NSNull null] : [_rfc3339DateFormatter stringFromDate:visit.departureDate]
    }];
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    [self validateUpdatingLocation];
}

#pragma mark NSURLSessionDelegate
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^) (NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {

    if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {

        SecTrustRef serverTrust = [[challenge protectionSpace] serverTrust];
        SecTrustResultType trustResult;

        // Validate the certificate chain with the device's trust store anyway
        // This *might* give use revocation checking
        SecTrustEvaluate(serverTrust, &trustResult);
        if (trustResult == kSecTrustResultUnspecified)
        {
            // Look for a pinned certificate in the server's certificate chain
            long numKeys = SecTrustGetCertificateCount(serverTrust);

            BOOL found = false;
            // Try GeoTrust Cert First
            for (int lc = 0; lc < numKeys; lc++) {
                SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, lc);
                NSData *remoteCertificateData = CFBridgingRelease(SecCertificateCopyData(certificate));

                // Compare Remote Key With Local Version
                if ([remoteCertificateData isEqualToData:_geoTrustCert]) {
                    // Found the certificate; continue connecting
                    completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
                    found = true;
                    break;
                }
            }

            if (!found) {
                // Fallback to Digicert Cert
                for (int lc = 0; lc < numKeys; lc++) {
                    SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, lc);
                    NSData *remoteCertificateData = CFBridgingRelease(SecCertificateCopyData(certificate));

                    // Compare Remote Key With Local Version
                    if ([remoteCertificateData isEqualToData:_digicertCert]) {
                        // Found the certificate; continue connecting
                        completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
                        found = true;
                        break;
                    }
                }

                if (!found) {
                    // The certificate wasn't found in GeoTrust nor Digicert. Cancel the connection.
                    completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
                }
            }
        }
        else
        {
            // Certificate chain validation failed; cancel the connection
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
        }
    }
    
}

@end