From 4837359471bb7c55d685dcd626eceb41cec1de67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Minh=20Nguy=E1=BB=85n?= Date: Fri, 8 May 2015 12:52:08 -0700 Subject: [PATCH 01/15] Register default user defaults on class initialization `-[MGLMapboxEvents init]` only gets called if `-[MGLMapboxEvents sharedManager]` sees that user defaults call for an `MGLMapboxEvents` to be created. But those user defaults were only being registered inside `-[MGLMapboxEvents init]`. This change moves the registration to `+initialize`, which is called as soon as the class is loaded. --- platform/ios/MGLMapboxEvents.m | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/platform/ios/MGLMapboxEvents.m b/platform/ios/MGLMapboxEvents.m index 3a6559b76..7890a7f53 100644 --- a/platform/ios/MGLMapboxEvents.m +++ b/platform/ios/MGLMapboxEvents.m @@ -109,15 +109,9 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; @implementation MGLMapboxEvents -// Must be called from the main thread. Only called internally. -// -- (instancetype) init { - MGLAssertIsMainThread(); - - self = [super init]; - if (self) { - - // Put Settings bundle into memory ++ (void)initialize { + if (self == [MGLMapboxEvents class]) { + // Register defaults from DefaultValue entries in Settings.bundle plist. NSString *appSettingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"]; if(!appSettingsBundle) { NSLog(@"Could not find Settings.bundle"); @@ -136,6 +130,16 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; [[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister]; } + } +} + +// Must be called from the main thread. Only called internally. +// +- (instancetype) init { + MGLAssertIsMainThread(); + + self = [super init]; + if (self) { _appBundleId = [[NSBundle mainBundle] bundleIdentifier]; NSString *uniqueID = [[NSProcessInfo processInfo] globallyUniqueString]; _serialQueue = dispatch_queue_create([[NSString stringWithFormat:@"%@.%@.events.serial", _appBundleId, uniqueID] UTF8String], DISPATCH_QUEUE_SERIAL); From 1503f33140e97090ccf53172853b4af10760deb0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Minh=20Nguy=E1=BB=85n?= Date: Fri, 8 May 2015 12:57:04 -0700 Subject: [PATCH 02/15] Predicate MGLMapboxEvents initialization on user opt-out --- platform/ios/MGLMapboxEvents.m | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/platform/ios/MGLMapboxEvents.m b/platform/ios/MGLMapboxEvents.m index 7890a7f53..1439293e2 100644 --- a/platform/ios/MGLMapboxEvents.m +++ b/platform/ios/MGLMapboxEvents.m @@ -225,6 +225,7 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; static MGLMapboxEvents *_sharedManager; dispatch_once(&onceToken, ^{ if ( ! NSProcessInfo.processInfo.mgl_isInterfaceBuilderDesignablesAgent && + [[NSUserDefaults standardUserDefaults] boolForKey:@"MGLMapboxMetricsEnabled"] && [[NSUserDefaults standardUserDefaults] integerForKey:@"MGLMapboxAccountType"] == 0) { void (^setupBlock)() = ^{ _sharedManager = [[self alloc] init]; @@ -330,12 +331,6 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; MGLMapboxEvents *strongSelf = weakSelf; if ( ! strongSelf) return; - // User has opted out - if (![[NSUserDefaults standardUserDefaults] boolForKey:@"MGLMapboxMetricsEnabled"]) { - [_eventQueue removeAllObjects]; - return; - } - // Metrics Collection Has Been Paused if (_paused) { return; From 60ed9e6d2ebdeef233cb6891a26f5b24e0efaaef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Minh=20Nguy=E1=BB=85n?= Date: Fri, 8 May 2015 14:25:54 -0700 Subject: [PATCH 03/15] Objective-C method naming convention MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Removed “get” from names of methods that perform no network or file access. --- platform/ios/MGLMapboxEvents.m | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/platform/ios/MGLMapboxEvents.m b/platform/ios/MGLMapboxEvents.m index 1439293e2..82111fe6e 100644 --- a/platform/ios/MGLMapboxEvents.m +++ b/platform/ios/MGLMapboxEvents.m @@ -189,7 +189,7 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; } _vendorId = [[[UIDevice currentDevice] identifierForVendor] UUIDString]; - _model = [self getSysInfoByName:"hw.machine"]; + _model = [self sysInfoByName:"hw.machine"]; _iOSVersion = [NSString stringWithFormat:@"%@ %@", [UIDevice currentDevice].systemName, [UIDevice currentDevice].systemVersion]; if ([UIScreen instancesRespondToSelector:@selector(nativeScale)]) { _scale = [UIScreen mainScreen].nativeScale; @@ -351,26 +351,26 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; // mapbox-events-ios stock attributes [evt setValue:strongSelf.model forKey:@"model"]; [evt setValue:strongSelf.iOSVersion forKey:@"operatingSystem"]; - [evt setValue:[strongSelf getDeviceOrientation] forKey:@"orientation"]; + [evt setValue:[strongSelf deviceOrientation] forKey:@"orientation"]; [evt setValue:@((int)(100 * [UIDevice currentDevice].batteryLevel)) forKey:@"batteryLevel"]; [evt setValue:@(strongSelf.scale) forKey:@"resolution"]; [evt setValue:strongSelf.carrier forKey:@"carrier"]; - NSString *cell = [strongSelf getCurrentCellularNetworkConnectionType]; + NSString *cell = [strongSelf currentCellularNetworkConnectionType]; if (cell) { [evt setValue:cell forKey:@"cellularNetworkType"]; } else { [evt setObject:[NSNull null] forKey:@"cellularNetworkType"]; } - NSString *wifi = [strongSelf getWifiNetworkName]; + NSString *wifi = [strongSelf wifiNetworkName]; if (wifi) { [evt setValue:wifi forKey:@"wifi"]; } else { [evt setObject:[NSNull null] forKey:@"wifi"]; } - [evt setValue:@([strongSelf getContentSizeScale]) forKey:@"accessibilityFontScale"]; + [evt setValue:@([strongSelf contentSizeScale]) forKey:@"accessibilityFontScale"]; // Make Immutable Version NSDictionary *finalEvent = [NSDictionary dictionaryWithDictionary:evt]; @@ -437,7 +437,7 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; // Setup URL Request NSString *url = [NSString stringWithFormat:@"%@/events/v1?access_token=%@", MGLMapboxEventsAPIBase, strongSelf.token]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]]; - [request setValue:[strongSelf getUserAgent] forHTTPHeaderField:@"User-Agent"]; + [request setValue:strongSelf.userAgent forHTTPHeaderField:@"User-Agent"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setHTTPMethod:@"POST"]; @@ -482,11 +482,11 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; // Can be called from any thread. // -- (NSString *) getUserAgent { - if (self.appName != nil && self.appVersion != nil && self.appBuildNumber != nil && ([self.userAgent rangeOfString:self.appName].location == NSNotFound)) { - self.userAgent = [NSString stringWithFormat:@"%@/%@/%@ %@", self.appName, self.appVersion, self.appBuildNumber, self.userAgent]; +- (NSString *) userAgent { + if (self.appName != nil && self.appVersion != nil && self.appBuildNumber != nil && ([_userAgent rangeOfString:self.appName].location == NSNotFound)) { + _userAgent = [NSString stringWithFormat:@"%@/%@/%@ %@", self.appName, self.appVersion, self.appBuildNumber, _userAgent]; } - return self.userAgent; + return _userAgent; } // Can be called from any thread. @@ -497,7 +497,7 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; // Can be called from any thread. // -- (NSString *) getDeviceOrientation { +- (NSString *) deviceOrientation { __block NSString *result; NSString *(^deviceOrientationBlock)(void) = ^{ @@ -544,7 +544,7 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; // Can be called from any thread. // -- (NSInteger) getContentSizeScale { +- (NSInteger) contentSizeScale { __block NSInteger result = -9999; NSInteger (^contentSizeScaleBlock)(void) = ^{ @@ -592,7 +592,7 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; // Can be called from any thread. // -- (NSString *)getSysInfoByName:(char *)typeSpecifier +- (NSString *)sysInfoByName:(char *)typeSpecifier { size_t size; sysctlbyname(typeSpecifier, NULL, &size, NULL, 0); @@ -608,7 +608,7 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; // Can be called from any thread. // -- (NSString *) getWifiNetworkName { +- (NSString *) wifiNetworkName { NSString *ssid = nil; CFArrayRef interfaces = CNCopySupportedInterfaces(); @@ -625,7 +625,7 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; // Can be called from any thread. // -- (NSString *) getCurrentCellularNetworkConnectionType { +- (NSString *) currentCellularNetworkConnectionType { CTTelephonyNetworkInfo *telephonyInfo = [[CTTelephonyNetworkInfo alloc] init]; NSString *radioTech = telephonyInfo.currentRadioAccessTechnology; From f860169f356af37536443d8f23e8ccd610c21eb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Minh=20Nguy=E1=BB=85n?= Date: Fri, 8 May 2015 16:43:50 -0700 Subject: [PATCH 04/15] Refactored MGLMapboxEvents for better data management The shared `MGLMapboxEvents` now owns the only instance of `MGLMetricsLocationManager`. It also owns a `MGLMapboxEventsData` object, to which all user-specific data has been relegated. This object can be built up and torn down on the fly, whenever the opt-out preference is toggled. `MGLMapboxEvents` has also given up knowledge of the access token and now queries `MGLAccountManager` for that information, which `MGLMapView` keeps up-to-date. --- gyp/platform-ios.gypi | 1 + include/mbgl/ios/MGLMapboxEvents.h | 4 - include/mbgl/ios/MGLMetricsLocationManager.h | 9 - platform/ios/MGLAccountManager.m | 10 +- platform/ios/MGLMapView.mm | 11 +- platform/ios/MGLMapboxEvents.m | 230 +++++++++---------- platform/ios/MGLMapboxEvents_Private.h | 7 + platform/ios/MGLMetricsLocationManager.m | 13 +- 8 files changed, 130 insertions(+), 155 deletions(-) create mode 100644 platform/ios/MGLMapboxEvents_Private.h diff --git a/gyp/platform-ios.gypi b/gyp/platform-ios.gypi index 1f96f9470..81c73975a 100644 --- a/gyp/platform-ios.gypi +++ b/gyp/platform-ios.gypi @@ -19,6 +19,7 @@ '../platform/darwin/reachability.m', '../include/mbgl/ios/MapboxGL.h', '../include/mbgl/ios/MGLMapboxEvents.h', + '../platform/ios/MGLMapboxEvents_Private.h', '../platform/ios/MGLMapboxEvents.m', '../include/mbgl/ios/MGLMapView.h', '../include/mbgl/ios/MGLMapView+IBAdditions.h', diff --git a/include/mbgl/ios/MGLMapboxEvents.h b/include/mbgl/ios/MGLMapboxEvents.h index c70c7cb33..abbd3b4b4 100644 --- a/include/mbgl/ios/MGLMapboxEvents.h +++ b/include/mbgl/ios/MGLMapboxEvents.h @@ -32,10 +32,6 @@ extern NSString *const MGLEventGestureRotateStart; // You must call these methods from the main thread. // -+ (void) setToken:(NSString *)token; -+ (void) setAppName:(NSString *)appName; -+ (void) setAppVersion:(NSString *)appVersion; -+ (void) setAppBuildNumber:(NSString *)appBuildNumber; + (void) pauseMetricsCollection; + (void) resumeMetricsCollection; diff --git a/include/mbgl/ios/MGLMetricsLocationManager.h b/include/mbgl/ios/MGLMetricsLocationManager.h index f02c76f53..4161fc4dd 100644 --- a/include/mbgl/ios/MGLMetricsLocationManager.h +++ b/include/mbgl/ios/MGLMetricsLocationManager.h @@ -1,13 +1,4 @@ #import @interface MGLMetricsLocationManager : NSObject - -// These methods can be called from any thread. -// -+ (instancetype)sharedManager; -- (void) startUpdatingLocation; -- (void) stopUpdatingLocation; -- (void) startMonitoringVisits; -- (void) stopMonitoringVisits; - @end diff --git a/platform/ios/MGLAccountManager.m b/platform/ios/MGLAccountManager.m index b1a80fd6a..ad1e93d29 100644 --- a/platform/ios/MGLAccountManager.m +++ b/platform/ios/MGLAccountManager.m @@ -1,8 +1,8 @@ #import #import "MGLAccountManager.h" +#import "MGLMapboxEvents_Private.h" #import "NSProcessInfo+MGLAdditions.h" -#import "MGLMapboxEvents.h" @interface MGLAccountManager() @@ -17,7 +17,7 @@ static MGLAccountManager *_sharedManager; // Can be called from any thread. // -+ (instancetype) sharedInstance { ++ (instancetype) sharedManager { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ if ( ! NSProcessInfo.processInfo.mgl_isInterfaceBuilderDesignablesAgent) { @@ -38,15 +38,15 @@ static MGLAccountManager *_sharedManager; } + (void) setAccessToken:(NSString *) accessToken { - [[MGLAccountManager sharedInstance] setAccessToken:accessToken]; + [[MGLAccountManager sharedManager] setAccessToken:accessToken]; // Update MGLMapboxEvents // NOTE: This is (likely) the initial setup of MGLMapboxEvents - [MGLMapboxEvents setToken:accessToken]; + [MGLMapboxEvents sharedManager]; } + (NSString *) accessToken { - return [MGLAccountManager sharedInstance].accessToken; + return [MGLAccountManager sharedManager].accessToken; } diff --git a/platform/ios/MGLMapView.mm b/platform/ios/MGLMapView.mm index cd8547e22..80ef4a525 100644 --- a/platform/ios/MGLMapView.mm +++ b/platform/ios/MGLMapView.mm @@ -20,6 +20,7 @@ #import "NSString+MGLAdditions.h" #import "NSProcessInfo+MGLAdditions.h" #import "NSException+MGLAdditions.h" +#import "MGLAccountManager.h" #import "MGLAnnotation.h" #import "MGLUserLocationAnnotationView.h" #import "MGLUserLocation_Private.h" @@ -158,7 +159,7 @@ std::chrono::steady_clock::duration secondsAsDuration(float duration) - (void)setAccessToken:(NSString *)accessToken { _mbglMap->setAccessToken(accessToken ? (std::string)[accessToken UTF8String] : ""); - [MGLMapboxEvents setToken:accessToken.mgl_stringOrNilIfEmpty]; + [MGLAccountManager setAccessToken:accessToken.mgl_stringOrNilIfEmpty]; } + (NSSet *)keyPathsForValuesAffectingStyleURL @@ -211,14 +212,6 @@ std::chrono::steady_clock::duration secondsAsDuration(float duration) // self.accessibilityLabel = @"Map"; - // metrics: initial setup - NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"]; - NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; - NSString *appBuildNumber = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]; - if (appName != nil) [MGLMapboxEvents setAppName:appName]; - if (appVersion != nil) [MGLMapboxEvents setAppVersion:appVersion]; - if (appBuildNumber != nil) [MGLMapboxEvents setAppBuildNumber:appBuildNumber]; - // create GL view // _glView = [[GLKView alloc] initWithFrame:self.bounds context:_context]; diff --git a/platform/ios/MGLMapboxEvents.m b/platform/ios/MGLMapboxEvents.m index 82111fe6e..d8d57daba 100644 --- a/platform/ios/MGLMapboxEvents.m +++ b/platform/ios/MGLMapboxEvents.m @@ -1,10 +1,11 @@ -#import "MGLMapboxEvents.h" +#import "MGLMapboxEvents_Private.h" #import #import #import #import +#import "MGLAccountManager.h" #import "MGLMetricsLocationManager.h" #import "NSProcessInfo+MGLAdditions.h" #import "NSBundle+MGLAdditions.h" @@ -43,6 +44,76 @@ NSString *const MGLEventGesturePanStart = @"Pan"; NSString *const MGLEventGesturePinchStart = @"Pinch"; NSString *const MGLEventGestureRotateStart = @"Rotation"; +@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: // @@ -64,26 +135,18 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; // All of the following properties are written to only from // the main thread, but can be read on any thread. // -@property (atomic) NSString *token; +@property (atomic) MGLMapboxEventsData *data; +@property (atomic) NSString *appBundleId; @property (atomic) NSString *appName; @property (atomic) NSString *appVersion; @property (atomic) NSString *appBuildNumber; -@property (atomic) NSString *instanceID; -@property (atomic) NSString *advertiserId; -@property (atomic) NSString *vendorId; -@property (atomic) NSString *appBundleId; -@property (atomic) NSString *userAgent; -@property (atomic) NSString *model; -@property (atomic) NSString *iOSVersion; -@property (atomic) NSString *carrier; +@property (atomic) MGLMetricsLocationManager *locationManager; @property (atomic) NSUInteger flushAt; @property (atomic) NSDateFormatter *rfc3339DateFormatter; -@property (atomic) CGFloat scale; @property (atomic) NSURLSession *session; @property (atomic) NSData *digicertCert; @property (atomic) NSData *geoTrustCert; - // The paused state tracker is only ever accessed from the main thread. // @property (nonatomic, getter=isPaused) BOOL paused; @@ -133,6 +196,12 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; } } ++ (BOOL)isEnabled { + return ( ! NSProcessInfo.processInfo.mgl_isInterfaceBuilderDesignablesAgent && + [[NSUserDefaults standardUserDefaults] boolForKey:@"MGLMapboxMetricsEnabled"] && + [[NSUserDefaults standardUserDefaults] integerForKey:@"MGLMapboxAccountType"] == 0); +} + // Must be called from the main thread. Only called internally. // - (instancetype) init { @@ -141,6 +210,10 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; self = [super init]; if (self) { _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); @@ -168,38 +241,6 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; _eventQueue = [[NSMutableArray alloc] init]; _flushAt = 20; _flushAfter = 60; - _token = nil; - _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]; - - _userAgent = MGLMapboxEventsUserAgent; // Setup Date Format _rfc3339DateFormatter = [[NSDateFormatter alloc] init]; @@ -224,20 +265,16 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; static dispatch_once_t onceToken; static MGLMapboxEvents *_sharedManager; dispatch_once(&onceToken, ^{ - if ( ! NSProcessInfo.processInfo.mgl_isInterfaceBuilderDesignablesAgent && - [[NSUserDefaults standardUserDefaults] boolForKey:@"MGLMapboxMetricsEnabled"] && - [[NSUserDefaults standardUserDefaults] integerForKey:@"MGLMapboxAccountType"] == 0) { - void (^setupBlock)() = ^{ - _sharedManager = [[self alloc] init]; - }; - if ( ! [[NSThread currentThread] isMainThread]) { - dispatch_sync(dispatch_get_main_queue(), ^{ - setupBlock(); - }); - } - else { + void (^setupBlock)() = ^{ + _sharedManager = [[self alloc] init]; + }; + if ( ! [[NSThread currentThread] isMainThread]) { + dispatch_sync(dispatch_get_main_queue(), ^{ setupBlock(); - } + }); + } + else { + setupBlock(); } }); return _sharedManager; @@ -247,34 +284,6 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; [self pauseMetricsCollection]; } -// Must be called from the main thread. -// -+ (void) setToken:(NSString *)token { - MGLAssertIsMainThread(); - [MGLMapboxEvents sharedManager].token = token; -} - -// Must be called from the main thread. -// -+ (void) setAppName:(NSString *)appName { - MGLAssertIsMainThread(); - [MGLMapboxEvents sharedManager].appName = appName; -} - -// Must be called from the main thread. -// -+ (void) setAppVersion:(NSString *)appVersion { - MGLAssertIsMainThread(); - [MGLMapboxEvents sharedManager].appVersion = appVersion; -} - -// Must be called from the main thread. -// -+ (void) setAppBuildNumber:(NSString *)appBuildNumber { - MGLAssertIsMainThread(); - [MGLMapboxEvents sharedManager].appBuildNumber = appBuildNumber; -} - + (void)pauseMetricsCollection { [[MGLMapboxEvents sharedManager] pauseMetricsCollection]; } @@ -287,11 +296,10 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; return; } self.paused = YES; + _data = nil; [_session invalidateAndCancel]; _session = nil; - MGLMetricsLocationManager *sharedLocationManager = [MGLMetricsLocationManager sharedManager]; - [sharedLocationManager stopUpdatingLocation]; - [sharedLocationManager stopMonitoringVisits]; + _locationManager = nil; } + (void)resumeMetricsCollection { @@ -302,14 +310,13 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; // - (void)resumeMetricsCollection { MGLAssertIsMainThread(); - if (!self.isPaused) { + if (!self.isPaused || [[self class] isEnabled]) { return; } self.paused = NO; + _data = [[MGLMapboxEventsData alloc] init]; _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil]; - MGLMetricsLocationManager *sharedLocationManager = [MGLMetricsLocationManager sharedManager]; - [sharedLocationManager startUpdatingLocation]; - [sharedLocationManager startMonitoringVisits]; + _locationManager = [[MGLMetricsLocationManager alloc] init]; } // Can be called from any thread. Can be called rapidly from @@ -343,18 +350,18 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; [evt setObject:event forKey:@"event"]; [evt setObject:@(1) forKey:@"version"]; [evt setObject:[strongSelf.rfc3339DateFormatter stringFromDate:[NSDate date]] forKey:@"created"]; - [evt setObject:strongSelf.instanceID forKey:@"instance"]; - [evt setObject:strongSelf.advertiserId forKey:@"advertiserId"]; - [evt setObject:strongSelf.vendorId forKey:@"vendorId"]; + [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.model forKey:@"model"]; - [evt setValue:strongSelf.iOSVersion forKey:@"operatingSystem"]; + [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.scale) forKey:@"resolution"]; - [evt setValue:strongSelf.carrier forKey:@"carrier"]; + [evt setValue:@(strongSelf.data.scale) forKey:@"resolution"]; + [evt setValue:strongSelf.data.carrier forKey:@"carrier"]; NSString *cell = [strongSelf currentCellularNetworkConnectionType]; if (cell) { @@ -397,7 +404,7 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; // Can be called from any thread. // - (void) flush { - if (self.token == nil) return; + if ([MGLAccountManager accessToken] == nil) return; __weak MGLMapboxEvents *weakSelf = self; @@ -435,7 +442,7 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; if (!strongSelf) return; // Setup URL Request - NSString *url = [NSString stringWithFormat:@"%@/events/v1?access_token=%@", MGLMapboxEventsAPIBase, strongSelf.token]; + 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"]; @@ -483,10 +490,7 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; // Can be called from any thread. // - (NSString *) userAgent { - if (self.appName != nil && self.appVersion != nil && self.appBuildNumber != nil && ([_userAgent rangeOfString:self.appName].location == NSNotFound)) { - _userAgent = [NSString stringWithFormat:@"%@/%@/%@ %@", self.appName, self.appVersion, self.appBuildNumber, _userAgent]; - } - return _userAgent; + return [NSString stringWithFormat:@"%@/%@/%@ %@", self.appName, self.appVersion, self.appBuildNumber, MGLMapboxEventsUserAgent]; } // Can be called from any thread. @@ -590,22 +594,6 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; return result; } -// 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; -} - // Can be called from any thread. // - (NSString *) wifiNetworkName { diff --git a/platform/ios/MGLMapboxEvents_Private.h b/platform/ios/MGLMapboxEvents_Private.h new file mode 100644 index 000000000..6a48b31f0 --- /dev/null +++ b/platform/ios/MGLMapboxEvents_Private.h @@ -0,0 +1,7 @@ +#import "MGLMapboxEvents.h" + +@interface MGLMapboxEvents (Private) + ++ (instancetype)sharedManager; + +@end diff --git a/platform/ios/MGLMetricsLocationManager.m b/platform/ios/MGLMetricsLocationManager.m index 9c186e4bf..ce4990740 100644 --- a/platform/ios/MGLMetricsLocationManager.m +++ b/platform/ios/MGLMetricsLocationManager.m @@ -27,17 +27,16 @@ // Clear Any System TimeZone Cache [NSTimeZone resetSystemTimeZone]; [_rfc3339DateFormatter setTimeZone:[NSTimeZone systemTimeZone]]; + + [self startUpdatingLocation]; + [self startMonitoringVisits]; } return self; } -+ (instancetype)sharedManager { - static dispatch_once_t onceToken; - static MGLMetricsLocationManager *sharedManager; - dispatch_once(&onceToken, ^{ - sharedManager = [[self alloc] init]; - }); - return sharedManager; +- (void)dealloc { + [self stopUpdatingLocation]; + [self stopMonitoringVisits]; } - (void)startUpdatingLocation { From c1fe6e18907b4edcb27fd7378091123e90d4e68f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Minh=20Nguy=E1=BB=85n?= Date: Sat, 9 May 2015 00:17:05 -0700 Subject: [PATCH 05/15] Resume iff Metrics is enabled --- platform/ios/MGLMapboxEvents.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platform/ios/MGLMapboxEvents.m b/platform/ios/MGLMapboxEvents.m index d8d57daba..8eefd7c05 100644 --- a/platform/ios/MGLMapboxEvents.m +++ b/platform/ios/MGLMapboxEvents.m @@ -310,7 +310,7 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; // - (void)resumeMetricsCollection { MGLAssertIsMainThread(); - if (!self.isPaused || [[self class] isEnabled]) { + if (!self.isPaused || ![[self class] isEnabled]) { return; } self.paused = NO; From 2f02a6538e8b13b77072045c9872b0169e10afcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Minh=20Nguy=E1=BB=85n?= Date: Sat, 9 May 2015 00:19:20 -0700 Subject: [PATCH 06/15] Folded MGLMetricsLocationManager into MGLMapboxEvents `MGLMetricsLocationManager` was nothing but overhead for `CLLocationManager`. Also removed an unused method. --- gyp/platform-ios.gypi | 2 - include/mbgl/ios/MGLMetricsLocationManager.h | 4 - platform/ios/MGLMapboxEvents.m | 83 +++++++++++++-- platform/ios/MGLMetricsLocationManager.m | 106 ------------------- 4 files changed, 73 insertions(+), 122 deletions(-) delete mode 100644 include/mbgl/ios/MGLMetricsLocationManager.h delete mode 100644 platform/ios/MGLMetricsLocationManager.m diff --git a/gyp/platform-ios.gypi b/gyp/platform-ios.gypi index 81c73975a..7e91648c4 100644 --- a/gyp/platform-ios.gypi +++ b/gyp/platform-ios.gypi @@ -34,8 +34,6 @@ '../platform/ios/MGLUserLocation.m', '../platform/ios/MGLUserLocationAnnotationView.h', '../platform/ios/MGLUserLocationAnnotationView.m', - '../include/mbgl/ios/MGLMetricsLocationManager.h', - '../platform/ios/MGLMetricsLocationManager.m', '../include/mbgl/ios/MGLTypes.h', '../platform/ios/NSBundle+MGLAdditions.h', '../platform/ios/NSBundle+MGLAdditions.m', diff --git a/include/mbgl/ios/MGLMetricsLocationManager.h b/include/mbgl/ios/MGLMetricsLocationManager.h deleted file mode 100644 index 4161fc4dd..000000000 --- a/include/mbgl/ios/MGLMetricsLocationManager.h +++ /dev/null @@ -1,4 +0,0 @@ -#import - -@interface MGLMetricsLocationManager : NSObject -@end diff --git a/platform/ios/MGLMapboxEvents.m b/platform/ios/MGLMapboxEvents.m index 8eefd7c05..74693f5c0 100644 --- a/platform/ios/MGLMapboxEvents.m +++ b/platform/ios/MGLMapboxEvents.m @@ -4,9 +4,9 @@ #import #import #import +#import #import "MGLAccountManager.h" -#import "MGLMetricsLocationManager.h" #import "NSProcessInfo+MGLAdditions.h" #import "NSBundle+MGLAdditions.h" #import "NSException+MGLAdditions.h" @@ -130,7 +130,7 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; // strong references. // -@interface MGLMapboxEvents() +@interface MGLMapboxEvents () // All of the following properties are written to only from // the main thread, but can be read on any thread. @@ -140,13 +140,15 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; @property (atomic) NSString *appName; @property (atomic) NSString *appVersion; @property (atomic) NSString *appBuildNumber; -@property (atomic) MGLMetricsLocationManager *locationManager; @property (atomic) NSUInteger flushAt; @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; @@ -299,6 +301,18 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; _data = nil; [_session invalidateAndCancel]; _session = nil; + + [self stopUpdatingLocation]; +} + +- (void)stopUpdatingLocation { + [_locationManager stopUpdatingLocation]; + + // -[CLLocationManager stopMonitoringVisits] is only available in iOS 8+. + if ([_locationManager respondsToSelector:@selector(stopMonitoringVisits)]) { + [_locationManager stopMonitoringVisits]; + } + _locationManager = nil; } @@ -316,7 +330,22 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; self.paused = NO; _data = [[MGLMapboxEventsData alloc] init]; _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil]; - _locationManager = [[MGLMetricsLocationManager alloc] init]; + + [self startUpdatingLocation]; +} + +- (void)startUpdatingLocation { + _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 @@ -493,12 +522,6 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; return [NSString stringWithFormat:@"%@/%@/%@ %@", self.appName, self.appVersion, self.appBuildNumber, MGLMapboxEventsUserAgent]; } -// Can be called from any thread. -// -- (NSString *) formatDate:(NSDate *)date { - return [self.rfc3339DateFormatter stringFromDate:date]; -} - // Can be called from any thread. // - (NSString *) deviceOrientation { @@ -678,6 +701,46 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; 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 { + switch (status) { + case kCLAuthorizationStatusDenied: + [self stopUpdatingLocation]; + break; + case kCLAuthorizationStatusAuthorized: + case kCLAuthorizationStatusAuthorizedWhenInUse: + [self startUpdatingLocation]; + break; + default: + break; + } +} + #pragma mark NSURLSessionDelegate - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^) (NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { diff --git a/platform/ios/MGLMetricsLocationManager.m b/platform/ios/MGLMetricsLocationManager.m deleted file mode 100644 index ce4990740..000000000 --- a/platform/ios/MGLMetricsLocationManager.m +++ /dev/null @@ -1,106 +0,0 @@ -#import "MGLMapboxEvents.h" -#import "MGLMetricsLocationManager.h" - -#import - -@interface MGLMetricsLocationManager() - -@property (nonatomic) CLLocationManager *locationManager; -@property (atomic) NSDateFormatter *rfc3339DateFormatter; - -@end - -@implementation MGLMetricsLocationManager - -- (instancetype) init { - if (self = [super init]) { - _locationManager = [[CLLocationManager alloc] init]; - _locationManager.desiredAccuracy = kCLLocationAccuracyKilometer; - _locationManager.distanceFilter = 10; - [_locationManager setDelegate:self]; - - _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]]; - - [self startUpdatingLocation]; - [self startMonitoringVisits]; - } - return self; -} - -- (void)dealloc { - [self stopUpdatingLocation]; - [self stopMonitoringVisits]; -} - -- (void)startUpdatingLocation { - [self.locationManager startUpdatingLocation]; -} - -- (void)stopUpdatingLocation { - [self.locationManager stopUpdatingLocation]; -} - -- (void)startMonitoringVisits { - // -[CLLocationManager startMonitoringVisits] is only available in iOS 8+. - if ([self.locationManager respondsToSelector:@selector(startMonitoringVisits)]) { - [self.locationManager startMonitoringVisits]; - } -} - -- (void)stopMonitoringVisits { - // -[CLLocationManager stopMonitoringVisits] is only available in iOS 8+. - if ([self.locationManager respondsToSelector:@selector(stopMonitoringVisits)]) { - [self.locationManager stopMonitoringVisits]; - } -} - -#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 { - switch (status) { - case kCLAuthorizationStatusDenied: - [self stopUpdatingLocation]; - [self stopMonitoringVisits]; - break; - case kCLAuthorizationStatusAuthorized: - case kCLAuthorizationStatusAuthorizedWhenInUse: - [self startUpdatingLocation]; - [self startMonitoringVisits]; - break; - default: - break; - } -} - -@end From ff0ec15e1d3544bd7c2b7aee868fc9017aaba661 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Minh=20Nguy=E1=BB=85n?= Date: Sat, 9 May 2015 00:51:00 -0700 Subject: [PATCH 07/15] More cleanup and sanitization Moved constant values from ivars into constants. Invalidate the flush timer and clear the event queue on pause. Rewrote some flush logic to be easier to follow. --- platform/ios/MGLMapboxEvents.m | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/platform/ios/MGLMapboxEvents.m b/platform/ios/MGLMapboxEvents.m index 74693f5c0..310283c5c 100644 --- a/platform/ios/MGLMapboxEvents.m +++ b/platform/ios/MGLMapboxEvents.m @@ -44,6 +44,9 @@ 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 @@ -140,7 +143,6 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; @property (atomic) NSString *appName; @property (atomic) NSString *appVersion; @property (atomic) NSString *appBuildNumber; -@property (atomic) NSUInteger flushAt; @property (atomic) NSDateFormatter *rfc3339DateFormatter; @property (atomic) NSURLSession *session; @property (atomic) NSData *digicertCert; @@ -157,10 +159,6 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; // @property (nonatomic) NSTimer *timer; -// The flush expiration time is only ever accessed from the main thread. -// -@property (nonatomic) NSTimeInterval flushAfter; - // This is an array of events to push. All access to it will be // from our own serial queue. // @@ -241,8 +239,6 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; // Events Control _eventQueue = [[NSMutableArray alloc] init]; - _flushAt = 20; - _flushAfter = 60; // Setup Date Format _rfc3339DateFormatter = [[NSDateFormatter alloc] init]; @@ -298,6 +294,9 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; return; } self.paused = YES; + [_timer invalidate]; + _timer = nil; + [_eventQueue removeAllObjects]; _data = nil; [_session invalidateAndCancel]; _session = nil; @@ -415,7 +414,7 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; [_eventQueue addObject:finalEvent]; // Has Flush Limit Been Reached? - if (_eventQueue.count >= strongSelf.flushAt) { + if (_eventQueue.count >= MGLMaximumEventsPerFlush) { [strongSelf flush]; } else if (_eventQueue.count == 1) { // If this is first new event on queue start timer, @@ -439,12 +438,10 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; dispatch_async(_serialQueue, ^{ MGLMapboxEvents *strongSelf = weakSelf; - if ( ! strongSelf) return; - - __block NSArray *events; + if ( ! strongSelf || [_eventQueue count] == 0) return; // Make an immutable copy - events = [NSArray arrayWithArray:_eventQueue]; + NSArray *events = [NSArray arrayWithArray:_eventQueue]; // Update Queue to remove events sent to server [_eventQueue removeAllObjects]; @@ -494,14 +491,11 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; - (void) startTimer { void (^timerBlock)() = ^{ // Stop Timer if it already exists - if (_timer) { - [_timer invalidate]; - _timer = nil; - } + [_timer invalidate]; // Start New Timer - _timer = [NSTimer scheduledTimerWithTimeInterval:_flushAfter - target:[self class] + _timer = [NSTimer scheduledTimerWithTimeInterval:MGLFlushInterval + target:self selector:@selector(flush) userInfo:nil repeats:YES]; From 58d695f6d31769437007e918fceb41a49b377001 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Minh=20Nguy=E1=BB=85n?= Date: Sat, 9 May 2015 01:28:24 -0700 Subject: [PATCH 08/15] Respond to opt-out setting change immediately As soon as the user returns to the host app after changing the opt-out preference in Settings, `MGLMapboxEvents` responds by pausing or resuming. Also moved the IB designables agent check to occur only once, at launch, since the process name is not expected to change mid-session. --- platform/ios/MGLMapboxEvents.m | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/platform/ios/MGLMapboxEvents.m b/platform/ios/MGLMapboxEvents.m index 310283c5c..e1c84efe6 100644 --- a/platform/ios/MGLMapboxEvents.m +++ b/platform/ios/MGLMapboxEvents.m @@ -170,7 +170,9 @@ const NSTimeInterval MGLFlushInterval = 60; @end -@implementation MGLMapboxEvents +@implementation MGLMapboxEvents { + id _userDefaultsObserver; +} + (void)initialize { if (self == [MGLMapboxEvents class]) { @@ -197,8 +199,7 @@ const NSTimeInterval MGLFlushInterval = 60; } + (BOOL)isEnabled { - return ( ! NSProcessInfo.processInfo.mgl_isInterfaceBuilderDesignablesAgent && - [[NSUserDefaults standardUserDefaults] boolForKey:@"MGLMapboxMetricsEnabled"] && + return ([[NSUserDefaults standardUserDefaults] boolForKey:@"MGLMapboxMetricsEnabled"] && [[NSUserDefaults standardUserDefaults] integerForKey:@"MGLMapboxAccountType"] == 0); } @@ -231,7 +232,6 @@ const NSTimeInterval MGLFlushInterval = 60; _geoTrustCert = [NSData dataWithContentsOfFile:cerPath]; } - cerPath = nil; cerPath = [resourceBundle pathForResource:@"api_mapbox_com-digicert" ofType:@"der"]; if (cerPath != nil) { _digicertCert = [NSData dataWithContentsOfFile:cerPath]; @@ -252,6 +252,21 @@ const NSTimeInterval MGLFlushInterval = 60; // 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; + BOOL enabledInSettings = [[strongSelf class] isEnabled]; + if (strongSelf.paused && enabledInSettings) { + [strongSelf resumeMetricsCollection]; + } else if (!strongSelf.paused && !enabledInSettings) { + [strongSelf pauseMetricsCollection]; + } + }]; } return self; } @@ -263,6 +278,10 @@ const NSTimeInterval MGLFlushInterval = 60; static dispatch_once_t onceToken; static MGLMapboxEvents *_sharedManager; dispatch_once(&onceToken, ^{ + if (NSProcessInfo.processInfo.mgl_isInterfaceBuilderDesignablesAgent) { + return; + } + void (^setupBlock)() = ^{ _sharedManager = [[self alloc] init]; }; @@ -279,6 +298,7 @@ const NSTimeInterval MGLFlushInterval = 60; } - (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:_userDefaultsObserver]; [self pauseMetricsCollection]; } From 54a703bcb21e567559caf691759bb207c611d776 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Minh=20Nguy=E1=BB=85n?= Date: Sat, 9 May 2015 10:33:08 -0700 Subject: [PATCH 09/15] Consolidated logic for pausing/resuming MGLMapboxEvents `MGLMapboxEvents` automatically recreates its location manager when the host app is reauthorized for Location Services. Added some redundancy to ensure that there is no location manager when either Location Services or Mapbox Metrics is off. --- include/mbgl/ios/MGLMapboxEvents.h | 3 ++ platform/ios/MGLMapView.mm | 2 + platform/ios/MGLMapboxEvents.m | 63 ++++++++++++++++++++---------- 3 files changed, 48 insertions(+), 20 deletions(-) diff --git a/include/mbgl/ios/MGLMapboxEvents.h b/include/mbgl/ios/MGLMapboxEvents.h index abbd3b4b4..5c5d8a924 100644 --- a/include/mbgl/ios/MGLMapboxEvents.h +++ b/include/mbgl/ios/MGLMapboxEvents.h @@ -54,4 +54,7 @@ extern NSString *const MGLEventGestureRotateStart; // + (void) flush; +// Main thread only ++ (void)validate; + @end diff --git a/platform/ios/MGLMapView.mm b/platform/ios/MGLMapView.mm index 80ef4a525..c928dd6ae 100644 --- a/platform/ios/MGLMapView.mm +++ b/platform/ios/MGLMapView.mm @@ -707,6 +707,8 @@ std::chrono::steady_clock::duration secondsAsDuration(float duration) if (self.isDormant) { self.dormant = NO; + + [MGLMapboxEvents validate]; self.glSnapshotView.hidden = YES; diff --git a/platform/ios/MGLMapboxEvents.m b/platform/ios/MGLMapboxEvents.m index e1c84efe6..89a13f7b5 100644 --- a/platform/ios/MGLMapboxEvents.m +++ b/platform/ios/MGLMapboxEvents.m @@ -260,12 +260,7 @@ const NSTimeInterval MGLFlushInterval = 60; usingBlock: ^(NSNotification *notification) { MGLMapboxEvents *strongSelf = weakSelf; - BOOL enabledInSettings = [[strongSelf class] isEnabled]; - if (strongSelf.paused && enabledInSettings) { - [strongSelf resumeMetricsCollection]; - } else if (!strongSelf.paused && !enabledInSettings) { - [strongSelf pauseMetricsCollection]; - } + [strongSelf validate]; }]; } return self; @@ -302,6 +297,38 @@ const NSTimeInterval MGLFlushInterval = 60; [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]; } @@ -321,7 +348,7 @@ const NSTimeInterval MGLFlushInterval = 60; [_session invalidateAndCancel]; _session = nil; - [self stopUpdatingLocation]; + [self validateUpdatingLocation]; } - (void)stopUpdatingLocation { @@ -343,17 +370,23 @@ const NSTimeInterval MGLFlushInterval = 60; // - (void)resumeMetricsCollection { MGLAssertIsMainThread(); - if (!self.isPaused || ![[self class] isEnabled]) { + if (!self.paused || ![[self class] isEnabled]) { return; } self.paused = NO; _data = [[MGLMapboxEventsData alloc] init]; _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil]; - [self startUpdatingLocation]; + [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; @@ -742,17 +775,7 @@ const NSTimeInterval MGLFlushInterval = 60; } - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status { - switch (status) { - case kCLAuthorizationStatusDenied: - [self stopUpdatingLocation]; - break; - case kCLAuthorizationStatusAuthorized: - case kCLAuthorizationStatusAuthorizedWhenInUse: - [self startUpdatingLocation]; - break; - default: - break; - } + [self validateUpdatingLocation]; } #pragma mark NSURLSessionDelegate From afbb9c27170475e28edb04a97fc92fef2160ea5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Minh=20Nguy=E1=BB=85n?= Date: Tue, 12 May 2015 15:26:07 -0700 Subject: [PATCH 10/15] Enable Metrics by default default default MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Enable Mapbox Metrics by default when Settings.bundle is absent, but allow Settings.bundle to override the default. Don’t register defaults for non-Mapbox preferences. The two-phase registration ensures that the defaults don’t default to unexpected values, yet gives the developer a chance to call `+[MGLAccountManager mapboxMetricsEnabledSettingShownInApp]` before the hard assertion. Fixes #1518. --- platform/ios/MGLMapboxEvents.m | 35 ++++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/platform/ios/MGLMapboxEvents.m b/platform/ios/MGLMapboxEvents.m index cb4cdce60..2864f0a49 100644 --- a/platform/ios/MGLMapboxEvents.m +++ b/platform/ios/MGLMapboxEvents.m @@ -110,6 +110,15 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; @implementation MGLMapboxEvents ++ (void)initialize { + if (self == [MGLMapboxEvents class]) { + [[NSUserDefaults standardUserDefaults] registerDefaults:@{ + @"MGLMapboxAccountType": @0, + @"MGLMapboxMetricsEnabled": @YES, + }]; + } +} + // Must be called from the main thread. Only called internally. // - (instancetype) init { @@ -121,23 +130,25 @@ NSString *const MGLEventGestureRotateStart = @"Rotation"; 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"]; - NSAssert(appSettingsBundle, @"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."); - - // 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 objectForKey:@"PreferenceSpecifiers"]; - NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]]; - for(NSDictionary *prefSpecification in preferences) { - NSString *key = [prefSpecification objectForKey:@"Key"]; - if(key && [[prefSpecification allKeys] containsObject:@"DefaultValue"]) { - [defaultsToRegister setObject:[prefSpecification objectForKey:@"DefaultValue"] forKey:key]; + 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"]; + } } } - [[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister]; + 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]; From 7ed31065ed9fb165d2467d17668fa7fe724d566a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Minh=20Nguy=E1=BB=85n?= Date: Tue, 12 May 2015 16:16:48 -0700 Subject: [PATCH 11/15] Cleaned up in-app opt-out property Renamed the property to be consistent with the public class methods. Also removed a spurious #import of a .m file. --- platform/ios/MGLAccountManager.m | 10 +++++----- platform/ios/MGLMapboxEvents.m | 1 - 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/platform/ios/MGLAccountManager.m b/platform/ios/MGLAccountManager.m index 0539fb9dc..9490e91ba 100644 --- a/platform/ios/MGLAccountManager.m +++ b/platform/ios/MGLAccountManager.m @@ -6,7 +6,7 @@ @interface MGLAccountManager() -@property (atomic) BOOL showsOptOutInApp; +@property (atomic) BOOL mapboxMetricsEnabledSettingShownInApp; @property (atomic) NSString *accessToken; @end @@ -24,7 +24,7 @@ static MGLAccountManager *_sharedManager; if ( ! NSProcessInfo.processInfo.mgl_isInterfaceBuilderDesignablesAgent) { void (^setupBlock)() = ^{ _sharedManager = [[self alloc] init]; - _sharedManager.showsOptOutInApp = NO; + _sharedManager.mapboxMetricsEnabledSettingShownInApp = NO; }; if ( ! [[NSThread currentThread] isMainThread]) { dispatch_sync(dispatch_get_main_queue(), ^{ @@ -39,12 +39,12 @@ static MGLAccountManager *_sharedManager; return _sharedManager; } -+ (void) setMapboxMetricsEnabledSettingShownInApp:(BOOL)showsOptOut { - [MGLAccountManager sharedManager].showsOptOutInApp = showsOptOut; ++ (void) setMapboxMetricsEnabledSettingShownInApp:(BOOL)shown { + [MGLAccountManager sharedManager].mapboxMetricsEnabledSettingShownInApp = shown; } + (BOOL) mapboxMetricsEnabledSettingShownInApp { - return [MGLAccountManager sharedManager].showsOptOutInApp; + return [MGLAccountManager sharedManager].mapboxMetricsEnabledSettingShownInApp; } + (void) setAccessToken:(NSString *) accessToken { diff --git a/platform/ios/MGLMapboxEvents.m b/platform/ios/MGLMapboxEvents.m index 12ed24359..fb9447972 100644 --- a/platform/ios/MGLMapboxEvents.m +++ b/platform/ios/MGLMapboxEvents.m @@ -10,7 +10,6 @@ #import "NSProcessInfo+MGLAdditions.h" #import "NSBundle+MGLAdditions.h" #import "NSException+MGLAdditions.h" -#import "MGLAccountManager.m" #include From 18b96ec4fdd46432d1c2f024b342b5833b342955 Mon Sep 17 00:00:00 2001 From: "Justin R. Miller" Date: Tue, 12 May 2015 16:33:32 -0700 Subject: [PATCH 12/15] fix spacing, ordering, imports --- include/mbgl/ios/MGLAccountManager.h | 4 +++- include/mbgl/ios/MapboxGL.h | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/include/mbgl/ios/MGLAccountManager.h b/include/mbgl/ios/MGLAccountManager.h index f8bb2bf9a..aed14a9d9 100644 --- a/include/mbgl/ios/MGLAccountManager.h +++ b/include/mbgl/ios/MGLAccountManager.h @@ -1,3 +1,5 @@ +#import + @interface MGLAccountManager : NSObject + (void) setMapboxMetricsEnabledSettingShownInApp:(BOOL)showsOptOut; @@ -5,4 +7,4 @@ + (void) setAccessToken:(NSString *) accessToken; + (NSString *) accessToken; -@end \ No newline at end of file +@end diff --git a/include/mbgl/ios/MapboxGL.h b/include/mbgl/ios/MapboxGL.h index 34e080a51..a6d23d328 100644 --- a/include/mbgl/ios/MapboxGL.h +++ b/include/mbgl/ios/MapboxGL.h @@ -1,5 +1,5 @@ +#import "MGLAccountManager.h" #import "MGLAnnotation.h" #import "MGLMapView.h" #import "MGLTypes.h" #import "MGLUserLocation.h" -#import "MGLAccountManager.h" \ No newline at end of file From efc4bb4ef6ded2e57ce6742c8dafa5d0ff87f2e0 Mon Sep 17 00:00:00 2001 From: "Justin R. Miller" Date: Tue, 12 May 2015 16:44:26 -0700 Subject: [PATCH 13/15] add header docs for new MGLAccountManager; reorg --- include/mbgl/ios/MGLAccountManager.h | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/include/mbgl/ios/MGLAccountManager.h b/include/mbgl/ios/MGLAccountManager.h index aed14a9d9..7ec4135f1 100644 --- a/include/mbgl/ios/MGLAccountManager.h +++ b/include/mbgl/ios/MGLAccountManager.h @@ -1,10 +1,29 @@ #import +/** The MGLAccountManager object provides a global way to set a Mapbox API access token, as well as other settings used framework-wide. */ @interface MGLAccountManager : NSObject -+ (void) setMapboxMetricsEnabledSettingShownInApp:(BOOL)showsOptOut; -+ (BOOL) mapboxMetricsEnabledSettingShownInApp; -+ (void) setAccessToken:(NSString *) accessToken; -+ (NSString *) accessToken; +/** @name Authorizing Access */ + +/** Set the Mapbox API access token for the framework. +* +* You can set an access token on MGLAccountManager or on an individual map view. The same token is used throughout the framework. +* @param accessToken The Mapbox API access token. */ ++ (void)setAccessToken:(NSString *)accessToken; + +/** Retreive the Mapbox API access token for the framework. +* +* You can set an access token on MGLAccountManager or on an individual map view. The same token is used throughout the framework. +* @return accessToken The Mapbox API access token. */ ++ (NSString *)accessToken; + +/** @name Providing User Metrics Opt-Out */ + +/** Certain Mapbox plans require the collection of user metrics. If you aren't using a preference switch in an existing or new `Settings.bundle` in your application, set this value to `YES` to indicate that you are providing a metrics opt-out for users within your app's interface directly. +* @param showsOptOut Whether your application's interface provides a user opt-out preference. The default value is `NO`, meaning a `Settings.bundle` is expected for providing a user opt-out preference. */ ++ (void)setMapboxMetricsEnabledSettingShownInApp:(BOOL)showsOptOut; + +/** Whether in-app user metrics opt-out is configured. If set to the default value of `NO`, a user opt-out preference is expected in a `Settings.bundle` that shows in the application's section within the system Settings app. */ ++ (BOOL)mapboxMetricsEnabledSettingShownInApp; @end From 1c8d3c5e425ddc60380767a40a2a505bc90249fa Mon Sep 17 00:00:00 2001 From: "Justin R. Miller" Date: Tue, 12 May 2015 17:14:29 -0700 Subject: [PATCH 14/15] patch up test project --- test/ios/ios-tests.xcodeproj/project.pbxproj | 2 ++ .../xcshareddata/ios-tests.xccheckout | 12 ++++++++++++ 2 files changed, 14 insertions(+) diff --git a/test/ios/ios-tests.xcodeproj/project.pbxproj b/test/ios/ios-tests.xcodeproj/project.pbxproj index d6c6344c2..50e12595f 100644 --- a/test/ios/ios-tests.xcodeproj/project.pbxproj +++ b/test/ios/ios-tests.xcodeproj/project.pbxproj @@ -631,6 +631,7 @@ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, "../../build/ios/pkg/static/**", OCMock, + OHHTTPStubs/OHHTTPStubs/Sources, ); INFOPLIST_FILE = "Bundle-Info.plist"; LIBRARY_SEARCH_PATHS = ( @@ -665,6 +666,7 @@ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, "../../build/ios/pkg/static/**", OCMock, + OHHTTPStubs/OHHTTPStubs/Sources, ); INFOPLIST_FILE = "Bundle-Info.plist"; LIBRARY_SEARCH_PATHS = ( diff --git a/test/ios/ios-tests.xcodeproj/project.xcworkspace/xcshareddata/ios-tests.xccheckout b/test/ios/ios-tests.xcodeproj/project.xcworkspace/xcshareddata/ios-tests.xccheckout index e2f98de8f..b6ff646f1 100644 --- a/test/ios/ios-tests.xcodeproj/project.xcworkspace/xcshareddata/ios-tests.xccheckout +++ b/test/ios/ios-tests.xcodeproj/project.xcworkspace/xcshareddata/ios-tests.xccheckout @@ -12,6 +12,8 @@ 10265E242415D473A6A613214DB7AC3EE3D43F93 https://github.com/mapbox/KIF.git + 38C2A0D4F62B675E8C16C8BC1437C7753846C8AC + https://github.com/AliSoftware/OHHTTPStubs.git 7E68CB584078A487C0535CC191D3B7551EEE2095 github.com:mapbox/mapbox-gl-native.git @@ -21,6 +23,8 @@ 10265E242415D473A6A613214DB7AC3EE3D43F93 ../../../..test/ios/KIF + 38C2A0D4F62B675E8C16C8BC1437C7753846C8AC + ../../../../test/ios/OHHTTPStubs/ 7E68CB584078A487C0535CC191D3B7551EEE2095 ../../../.. @@ -48,6 +52,14 @@ IDESourceControlWCCName KIF + + IDESourceControlRepositoryExtensionIdentifierKey + public.vcs.git + IDESourceControlWCCIdentifierKey + 38C2A0D4F62B675E8C16C8BC1437C7753846C8AC + IDESourceControlWCCName + OHHTTPStubs + From 190e91120927ea2e48a72c8337ba923dabe31f85 Mon Sep 17 00:00:00 2001 From: "Justin R. Miller" Date: Tue, 12 May 2015 18:23:59 -0700 Subject: [PATCH 15/15] fix dispatch-thread pattern 1. Always bail early if in IB. 2. Always run on main thread if not already. 3. THEN dispatch_once to create the static instance. --- platform/ios/MGLAccountManager.m | 36 ++++++++++++++++---------------- platform/ios/MGLMapboxEvents.m | 29 +++++++++++++------------ 2 files changed, 32 insertions(+), 33 deletions(-) diff --git a/platform/ios/MGLAccountManager.m b/platform/ios/MGLAccountManager.m index 9490e91ba..32540e4e4 100644 --- a/platform/ios/MGLAccountManager.m +++ b/platform/ios/MGLAccountManager.m @@ -14,28 +14,28 @@ @implementation MGLAccountManager -static MGLAccountManager *_sharedManager; - // Can be called from any thread. // + (instancetype) sharedManager { + if (NSProcessInfo.processInfo.mgl_isInterfaceBuilderDesignablesAgent) { + return; + } static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - if ( ! NSProcessInfo.processInfo.mgl_isInterfaceBuilderDesignablesAgent) { - void (^setupBlock)() = ^{ - _sharedManager = [[self alloc] init]; - _sharedManager.mapboxMetricsEnabledSettingShownInApp = NO; - }; - if ( ! [[NSThread currentThread] isMainThread]) { - dispatch_sync(dispatch_get_main_queue(), ^{ - setupBlock(); - }); - } - else { - setupBlock(); - } - } - }); + static MGLAccountManager *_sharedManager; + void (^setupBlock)() = ^{ + dispatch_once(&onceToken, ^{ + _sharedManager = [[self alloc] init]; + _sharedManager.mapboxMetricsEnabledSettingShownInApp = NO; + }); + }; + if ( ! [[NSThread currentThread] isMainThread]) { + dispatch_sync(dispatch_get_main_queue(), ^{ + setupBlock(); + }); + } + else { + setupBlock(); + } return _sharedManager; } diff --git a/platform/ios/MGLMapboxEvents.m b/platform/ios/MGLMapboxEvents.m index fb9447972..9fcfc7153 100644 --- a/platform/ios/MGLMapboxEvents.m +++ b/platform/ios/MGLMapboxEvents.m @@ -279,25 +279,24 @@ const NSTimeInterval MGLFlushInterval = 60; // 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; - dispatch_once(&onceToken, ^{ - if (NSProcessInfo.processInfo.mgl_isInterfaceBuilderDesignablesAgent) { - return; - } - - void (^setupBlock)() = ^{ + void (^setupBlock)() = ^{ + dispatch_once(&onceToken, ^{ _sharedManager = [[self alloc] init]; - }; - if ( ! [[NSThread currentThread] isMainThread]) { - dispatch_sync(dispatch_get_main_queue(), ^{ - setupBlock(); - }); - } - else { + }); + }; + if ( ! [[NSThread currentThread] isMainThread]) { + dispatch_sync(dispatch_get_main_queue(), ^{ setupBlock(); - } - }); + }); + } + else { + setupBlock(); + } return _sharedManager; }