[ios] Move source to src folder, matching osx

This commit is contained in:
John Firebaugh
2015-12-16 16:49:29 -08:00
parent 7a4e7376e1
commit a7e4e6bb1c
18 changed files with 19 additions and 19 deletions

View File

@@ -0,0 +1,109 @@
#import "MGLAccountManager_Private.h"
#import "MGLMapboxEvents.h"
#import "MGLCategoryLoader.h"
#import "NSProcessInfo+MGLAdditions.h"
#import "FABKitProtocol.h"
#import "Fabric+FABKits.h"
@interface MGLAccountManager() <FABKit>
@property (atomic) BOOL mapboxMetricsEnabledSettingShownInApp;
@property (atomic) NSString *accessToken;
@end
@implementation MGLAccountManager
#pragma mark - Internal
+ (void)load {
// Load all referenced categories due to absence of -ObjC linker flag
[MGLCategoryLoader loadCategories];
// Read the initial configuration from Info.plist. The shown-in-app setting
// preempts the Settings bundle check in -[MGLMapboxEvents init] triggered
// by setting the access token.
NSBundle *bundle = [NSBundle mainBundle];
NSNumber *shownInAppNumber = [bundle objectForInfoDictionaryKey:@"MGLMapboxMetricsEnabledSettingShownInApp"];
if (shownInAppNumber) {
[MGLAccountManager sharedManager].mapboxMetricsEnabledSettingShownInApp = [shownInAppNumber boolValue];
}
NSString *accessToken = [bundle objectForInfoDictionaryKey:@"MGLMapboxAccessToken"];
if (accessToken.length) {
self.accessToken = accessToken;
}
}
// Can be called from any thread.
//
+ (instancetype) sharedManager {
if (NSProcessInfo.processInfo.mgl_isInterfaceBuilderDesignablesAgent) {
return nil;
}
static dispatch_once_t onceToken;
static MGLAccountManager *_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;
}
+ (BOOL) mapboxMetricsEnabledSettingShownInApp {
return [MGLAccountManager sharedManager].mapboxMetricsEnabledSettingShownInApp;
}
+ (void) setAccessToken:(NSString *) accessToken {
accessToken = [accessToken stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ( ! [accessToken length]) return;
[MGLAccountManager sharedManager].accessToken = accessToken;
// Update MGLMapboxEvents
// NOTE: This is (likely) the initial setup of MGLMapboxEvents
[MGLMapboxEvents sharedManager];
}
+ (NSString *) accessToken {
return [MGLAccountManager sharedManager].accessToken;
}
#pragma mark - Fabric
+ (NSString *)bundleIdentifier {
return @"com.mapbox.sdk.ios";
}
+ (NSString *)kitDisplayVersion {
return @"3.0.1";
}
+ (void)initializeIfNeeded {
Class fabric = NSClassFromString(@"Fabric");
if (fabric) {
NSDictionary *configuration = [fabric configurationDictionaryForKitClass:[MGLAccountManager class]];
if ( ! configuration || ! configuration[@"accessToken"]) {
NSLog(@"Configuration dictionary returned by Fabric was nil or doesn't have accessToken. Can't initialize MGLAccountManager.");
return;
}
[self setAccessToken:configuration[@"accessToken"]];
MGLAccountManager *sharedAccountManager = [self sharedManager];
NSLog(@"MGLAccountManager was initialized with access token: %@", sharedAccountManager.accessToken);
} else {
NSLog(@"MGLAccountManager is used in a project that doesn't have Fabric.");
}
}
@end

View File

@@ -0,0 +1,10 @@
#import "MGLAccountManager.h"
@interface MGLAccountManager (Private)
/** Returns the shared instance of the `MGLAccountManager` class. */
+ (instancetype)sharedManager;
@property (atomic) NSString *accessToken;
@end

View File

@@ -0,0 +1,36 @@
#import "MGLAnnotationImage_Private.h"
@interface MGLAnnotationImage ()
@property (nonatomic, strong) NSString *reuseIdentifier;
@property (nonatomic, weak) id<MGLAnnotationImageDelegate> delegate;
@end
@implementation MGLAnnotationImage
+ (instancetype)annotationImageWithImage:(UIImage *)image reuseIdentifier:(NSString *)reuseIdentifier
{
return [[self alloc] initWithImage:image reuseIdentifier:reuseIdentifier];
}
- (instancetype)initWithImage:(UIImage *)image reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super init];
if (self)
{
_image = image;
_reuseIdentifier = [reuseIdentifier copy];
_enabled = YES;
}
return self;
}
- (void)setImage:(UIImage *)image {
_image = image;
[self.delegate annotationImageNeedsRedisplay:self];
}
@end

View File

@@ -0,0 +1,18 @@
#import "MGLAnnotationImage.h"
NS_ASSUME_NONNULL_BEGIN
@protocol MGLAnnotationImageDelegate <NSObject>
@required
- (void)annotationImageNeedsRedisplay:(MGLAnnotationImage *)annotationImage;
@end
@interface MGLAnnotationImage (Private)
@property (nonatomic, weak) id<MGLAnnotationImageDelegate> delegate;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,7 @@
#import <Foundation/Foundation.h>
@interface MGLCategoryLoader : NSObject
+ (void)loadCategories;
@end

View File

@@ -0,0 +1,24 @@
#import "MGLCategoryLoader.h"
#import "NSBundle+MGLAdditions.h"
#import "NSProcessInfo+MGLAdditions.h"
#import "NSString+MGLAdditions.h"
#import "MGLMapView.h"
@implementation MGLCategoryLoader
+ (void)loadCategories
{
// https://github.com/mapbox/mapbox-gl-native/issues/2966
//
mgl_linkBundleCategory();
mgl_linkProcessCategory();
mgl_linkStringCategory();
// https://github.com/mapbox/mapbox-gl-native/issues/3113
//
NSString *description = [MGLMapView description];
}
@end

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,73 @@
#import <Foundation/Foundation.h>
#import "MGLTypes.h"
NS_ASSUME_NONNULL_BEGIN
extern NSString *const MGLEventTypeAppUserTurnstile;
extern NSString *const MGLEventTypeMapLoad;
extern NSString *const MGLEventTypeMapTap;
extern NSString *const MGLEventTypeMapDragEnd;
extern NSString *const MGLEventTypeLocation;
extern NSString *const MGLEventTypeVisit;
extern NSString *const MGLEventKeyLatitude;
extern NSString *const MGLEventKeyLongitude;
extern NSString *const MGLEventKeyZoomLevel;
extern NSString *const MGLEventKeySpeed;
extern NSString *const MGLEventKeyCourse;
extern NSString *const MGLEventKeyAltitude;
extern NSString *const MGLEventKeyHorizontalAccuracy;
extern NSString *const MGLEventKeyVerticalAccuracy;
extern NSString *const MGLEventKeyPushEnabled;
extern NSString *const MGLEventKeyEmailEnabled;
extern NSString *const MGLEventKeyGestureID;
extern NSString *const MGLEventKeyArrivalDate;
extern NSString *const MGLEventKeyDepartureDate;
extern NSString *const MGLEventGestureSingleTap;
extern NSString *const MGLEventGestureDoubleTap;
extern NSString *const MGLEventGestureTwoFingerSingleTap;
extern NSString *const MGLEventGestureQuickZoom;
extern NSString *const MGLEventGesturePanStart;
extern NSString *const MGLEventGesturePinchStart;
extern NSString *const MGLEventGestureRotateStart;
extern NSString *const MGLEventGesturePitchStart;
typedef NS_DICTIONARY_OF(NSString *, id) MGLMapboxEventAttributes;
typedef NS_MUTABLE_DICTIONARY_OF(NSString *, id) MGLMutableMapboxEventAttributes;
@interface MGLMapboxEvents : NSObject <NSURLSessionDelegate>
+ (nullable instancetype)sharedManager;
// You must call these methods from the main thread.
//
+ (void) pauseMetricsCollection;
+ (void) resumeMetricsCollection;
// You can call this method from any thread. Significant work will
// be dispatched to a low-priority background queue and all
// resulting calls are guaranteed threadsafe.
//
// Events or attributes passed could be accessed on non-main threads,
// so you must not reference UI elements from within any arguments.
// Copy any values needed first or create dedicated methods in this
// class for threadsafe access to UIKit classes.
//
+ (void) pushEvent:(NSString *)event withAttributes:(MGLMapboxEventAttributes *)attributeDictionary;
// You can call these methods from any thread.
//
+ (BOOL) checkPushEnabled;
// You can call this method from any thread.
//
+ (void) flush;
// Main thread only
+ (void)validate;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,880 @@
#import "MGLMapboxEvents.h"
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#include <mbgl/platform/darwin/reachability.h>
#import "MGLAccountManager.h"
#import "NSProcessInfo+MGLAdditions.h"
#import "NSBundle+MGLAdditions.h"
#import "NSException+MGLAdditions.h"
#include <sys/sysctl.h>
static const NSUInteger version = 1;
static NSString *const MGLMapboxEventsUserAgent = @"MapboxEventsiOS/1.1";
static NSString *MGLMapboxEventsAPIBase = @"https://api.tiles.mapbox.com";
NSString *const MGLEventTypeAppUserTurnstile = @"appUserTurnstile";
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";
NSString *const MGLEventGesturePitchStart = @"Pitch";
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 *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]) {
_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;
}
}
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) NSString *instanceID;
@property (atomic) NSDateFormatter *rfc3339DateFormatter;
@property (atomic) NSURLSession *session;
@property (atomic) NSData *digicertCert;
@property (atomic) NSData *geoTrustCert;
@property (atomic) NSData *testServerCert;
@property (atomic) BOOL usesTestServer;
// 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) NS_MUTABLE_ARRAY_OF(MGLMapboxEventAttributes *) *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]) {
NSBundle *bundle = [NSBundle mainBundle];
NSNumber *accountTypeNumber = [bundle objectForInfoDictionaryKey:@"MGLMapboxAccountType"];
[[NSUserDefaults standardUserDefaults] registerDefaults:@{
@"MGLMapboxAccountType": accountTypeNumber ? accountTypeNumber : @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] &&
[[NSUserDefaults standardUserDefaults] integerForKey:@"MGLMapboxAccountType"] == 0) {
// 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"];
}
}
}
if (!defaultEnabledValue)
{
[NSException raise:@"MGLMapboxMetricsEnabled setting missing" format:
@"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 MGLMapboxMetricsEnabledSettingShownInApp to YES in Info.plist."];
}
[[NSUserDefaults standardUserDefaults] registerDefaults:@{
@"MGLMapboxMetricsEnabled": defaultEnabledValue,
}];
}
_appBundleId = [[NSBundle mainBundle] bundleIdentifier];
_appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
_appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
_appBuildNumber = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
_instanceID = [[NSUUID UUID] UUIDString];
NSString *uniqueID = [[NSProcessInfo processInfo] globallyUniqueString];
_serialQueue = dispatch_queue_create([[NSString stringWithFormat:@"%@.%@.events.serial", _appBundleId, uniqueID] UTF8String], DISPATCH_QUEUE_SERIAL);
// Configure Events Infrastructure
// ===============================
// Check for TEST Metrics URL
NSString *testURL = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"MGLMetricsTestServerURL"];
if (testURL != nil) {
MGLMapboxEventsAPIBase = testURL;
_usesTestServer = YES;
} else {
// Explicitly Set For Clarity
_usesTestServer = NO;
}
_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];
}
cerPath = [resourceBundle pathForResource:@"star_tilestream_net" ofType:@"der"];
if (cerPath != nil) {
_testServerCert = [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];
}];
// Turn the Mapbox Turnstile to Count App Users
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
[self pushTurnstileEvent];
});
}
return self;
}
// Can be called from any thread. Called implicitly from any
// public class convenience methods. May return nil if this feature is disabled.
//
+ (nullable instancetype)sharedManager {
if (NSProcessInfo.processInfo.mgl_isInterfaceBuilderDesignablesAgent) {
return nil;
}
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];
}
// Used to determine if Mapbox Metrics should be collected at any given point in time
- (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];
}
}
- (void) pushTurnstileEvent {
__weak MGLMapboxEvents *weakSelf = self;
dispatch_async(_serialQueue, ^{
MGLMapboxEvents *strongSelf = weakSelf;
if ( ! strongSelf) return;
// Build only IDFV event
NSString *vid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
NSDictionary *vevt = @{
@"event" : MGLEventTypeAppUserTurnstile,
@"created" : [strongSelf.rfc3339DateFormatter stringFromDate:[NSDate date]],
@"appBundleId" : strongSelf.appBundleId,
@"vendorId": vid,
@"version": @(version),
@"instance": strongSelf.instanceID
};
// Add to Queue
[_eventQueue addObject:vevt];
// Flush
[strongSelf flush];
});
}
// Can be called from any thread. Can be called rapidly from
// the UI thread, so performance is paramount.
//
+ (void) pushEvent:(NSString *)event withAttributes:(MGLMapboxEventAttributes *)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:(MGLMapboxEventAttributes *)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;
MGLMutableMapboxEventAttributes *evt = [MGLMutableMapboxEventAttributes dictionaryWithDictionary:attributeDictionary];
// mapbox-events stock attributes
[evt setObject:event forKey:@"event"];
[evt setObject:@(version) forKey:@"version"];
[evt setObject:[strongSelf.rfc3339DateFormatter stringFromDate:[NSDate date]] forKey:@"created"];
[evt setObject:strongSelf.instanceID forKey:@"instance"];
[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"];
MGLReachability *reachability = [MGLReachability reachabilityForLocalWiFi];
[evt setValue:([reachability isReachableViaWiFi] ? @YES : @NO) forKey:@"wifi"];
[evt setValue:[strongSelf applicationState] forKey:@"applicationState"];
[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:(NS_ARRAY_OF(MGLMapboxEventAttributes *) *)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
[[_session dataTaskWithRequest:request] 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.
//
- (NSString *) applicationState {
__block NSString *result;
NSString *(^applicationStateBlock)(void) = ^{
switch ([UIApplication sharedApplication].applicationState) {
case UIApplicationStateActive:
result = @"Active";
break;
case UIApplicationStateInactive:
result = @"Inactive";
break;
case UIApplicationStateBackground:
result = @"Background";
break;
default:
result = @"Default - Unknown";
break;
}
return result;
};
if ( ! [[NSThread currentThread] isMainThread]) {
dispatch_sync(dispatch_get_main_queue(), ^{
result = applicationStateBlock();
});
} else {
result = applicationStateBlock();
}
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.
//
+ (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: @(round(loc.altitude)),
MGLEventKeyHorizontalAccuracy: @(round(loc.horizontalAccuracy)),
MGLEventKeyVerticalAccuracy: @(round(loc.verticalAccuracy))
}];
}
}
- (void)locationManager:(CLLocationManager *)manager didVisit:(CLVisit *)visit {
[MGLMapboxEvents pushEvent:MGLEventTypeVisit withAttributes:@{
MGLEventKeyLatitude: @(visit.coordinate.latitude),
MGLEventKeyLongitude: @(visit.coordinate.longitude),
MGLEventKeyHorizontalAccuracy: @(round(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 = NO;
// 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 = YES;
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 = YES;
break;
}
}
if (!found && _usesTestServer) {
// See if this is test server
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:_testServerCert]) {
// Found the certificate; continue connecting
completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
found = YES;
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

View File

@@ -0,0 +1,74 @@
#import "MGLUserLocation_Private.h"
#import "MGLMapView.h"
NS_ASSUME_NONNULL_BEGIN
@interface MGLUserLocation ()
@property (nonatomic, weak) MGLMapView *mapView;
@end
NS_ASSUME_NONNULL_END
@implementation MGLUserLocation
- (instancetype)initWithMapView:(MGLMapView *)mapView
{
if (self = [super init])
{
_location = [[CLLocation alloc] initWithLatitude:MAXFLOAT longitude:MAXFLOAT];
_mapView = mapView;
}
return self;
}
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key
{
return ! [key isEqualToString:@"location"] && ! [key isEqualToString:@"heading"];
}
+ (NS_SET_OF(NSString *) *)keyPathsForValuesAffectingCoordinate
{
return [NSSet setWithObject:@"location"];
}
- (void)setLocation:(CLLocation *)newLocation
{
if ( ! newLocation || ! CLLocationCoordinate2DIsValid(newLocation.coordinate)) return;
if ( _location && CLLocationCoordinate2DIsValid(_location.coordinate) && [newLocation distanceFromLocation:_location] == 0) return;
if (newLocation.coordinate.latitude == 0 && newLocation.coordinate.longitude == 0) return;
[self willChangeValueForKey:@"location"];
_location = newLocation;
[self didChangeValueForKey:@"location"];
}
- (BOOL)isUpdating
{
return self.mapView.userTrackingMode != MGLUserTrackingModeNone;
}
- (void)setHeading:(CLHeading *)newHeading
{
if (newHeading.trueHeading != _heading.trueHeading)
{
[self willChangeValueForKey:@"heading"];
_heading = newHeading;
[self didChangeValueForKey:@"heading"];
}
}
- (CLLocationCoordinate2D)coordinate
{
return self.location.coordinate;
}
- (NSString *)title
{
return (_title ? _title : @"You Are Here");
}
@end

View File

@@ -0,0 +1,23 @@
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import "MGLTypes.h"
NS_ASSUME_NONNULL_BEGIN
@class MGLMapView;
@class MGLUserLocation;
/** View representing an MGLUserLocation on screen. */
@interface MGLUserLocationAnnotationView : UIView
@property (nonatomic, weak) MGLMapView *mapView;
@property (nonatomic) MGLUserLocation *annotation;
@property (nonatomic, readonly, nullable) CALayer *haloLayer;
- (instancetype)initInMapView:(MGLMapView *)mapView NS_DESIGNATED_INITIALIZER;
- (void)setupLayers;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,502 @@
#import "MGLUserLocationAnnotationView.h"
#import "MGLUserLocation.h"
#import "MGLUserLocation_Private.h"
#import "MGLAnnotation.h"
#import "MGLMapView.h"
const CGFloat MGLUserLocationAnnotationDotSize = 22.0;
const CGFloat MGLUserLocationAnnotationHaloSize = 115.0;
const CGFloat MGLUserLocationAnnotationPuckSize = 45.0;
const CGFloat MGLUserLocationAnnotationArrowSize = MGLUserLocationAnnotationPuckSize * 0.6;
@interface MGLUserLocationAnnotationView ()
@property (nonatomic, readwrite) CALayer *haloLayer;
@end
#pragma mark -
@implementation MGLUserLocationAnnotationView
{
BOOL _puckModeActivated;
CALayer *_puckDot;
CAShapeLayer *_puckArrow;
CALayer *_headingIndicatorLayer;
CAShapeLayer *_headingIndicatorMaskLayer;
CALayer *_accuracyRingLayer;
CALayer *_dotBorderLayer;
CALayer *_dotLayer;
double _oldHeadingAccuracy;
CLLocationAccuracy _oldHorizontalAccuracy;
double _oldZoom;
double _oldPitch;
}
- (instancetype)initWithFrame:(CGRect)frame
{
NSAssert(NO, @"No containing map view specified. Call -initInMapView: instead.");
return self = [self init];
}
- (instancetype)initInMapView:(MGLMapView *)mapView
{
CGFloat frameSize = (mapView.userTrackingMode == MGLUserTrackingModeFollowWithCourse) ? MGLUserLocationAnnotationPuckSize : MGLUserLocationAnnotationDotSize;
if (self = [super initWithFrame:CGRectMake(0, 0, frameSize, frameSize)])
{
self.annotation = [[MGLUserLocation alloc] initWithMapView:mapView];
_mapView = mapView;
[self setupLayers];
self.accessibilityLabel = @"User location";
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)decoder
{
MGLMapView *mapView = [decoder valueForKey:@"mapView"];
return [self initInMapView:mapView];
}
- (void)setTintColor:(UIColor *)tintColor
{
if (_puckModeActivated)
{
_puckArrow.fillColor = [tintColor CGColor];
}
else
{
if (_accuracyRingLayer)
{
_accuracyRingLayer.backgroundColor = [tintColor CGColor];
}
_haloLayer.backgroundColor = [tintColor CGColor];
_dotLayer.backgroundColor = [tintColor CGColor];
_headingIndicatorLayer.contents = (__bridge id)[[self headingIndicatorTintedGradientImage] CGImage];
}
}
- (void)setupLayers
{
if (CLLocationCoordinate2DIsValid(self.annotation.coordinate))
{
(_mapView.userTrackingMode == MGLUserTrackingModeFollowWithCourse) ? [self drawPuck] : [self drawDot];
[self updatePitch];
}
}
- (void)updatePitch
{
if (self.mapView.camera.pitch != _oldPitch)
{
CATransform3D t = CATransform3DRotate(CATransform3DIdentity, MGLRadiansFromDegrees(self.mapView.camera.pitch), 1.0, 0, 0);
self.layer.sublayerTransform = t;
[self updateFaux3DEffect];
_oldPitch = self.mapView.camera.pitch;
}
}
- (void)updateFaux3DEffect
{
CGFloat pitch = MGLRadiansFromDegrees(self.mapView.camera.pitch);
if (_puckDot)
{
_puckDot.shadowOffset = CGSizeMake(0, fmaxf(pitch * 10.f, 1.f));
_puckDot.shadowRadius = fmaxf(pitch * 5.f, 0.75f);
}
if (_dotBorderLayer)
{
_dotBorderLayer.shadowOffset = CGSizeMake(0.f, pitch * 10.f);
_dotBorderLayer.shadowRadius = fmaxf(pitch * 5.f, 3.f);
}
if (_dotLayer)
{
_dotLayer.zPosition = pitch * 2.f;
}
}
- (void)drawPuck
{
if ( ! _puckModeActivated)
{
self.layer.sublayers = nil;
_headingIndicatorLayer = nil;
_headingIndicatorMaskLayer = nil;
_accuracyRingLayer = nil;
_haloLayer = nil;
_dotBorderLayer = nil;
_dotLayer = nil;
}
// background dot (white with black shadow)
//
if ( ! _puckDot)
{
_puckDot = [self circleLayerWithSize:MGLUserLocationAnnotationPuckSize];
_puckDot.backgroundColor = [[UIColor whiteColor] CGColor];
_puckDot.shadowColor = [[UIColor blackColor] CGColor];
_puckDot.shadowOpacity = 0.25;
if (self.mapView.camera.pitch)
{
[self updateFaux3DEffect];
}
else
{
_puckDot.shadowOffset = CGSizeMake(0, 1);
_puckDot.shadowRadius = 0.75;
}
[self.layer addSublayer:_puckDot];
}
// arrow
//
if ( ! _puckArrow)
{
_puckArrow = [CAShapeLayer layer];
_puckArrow.path = [[self puckArrow] CGPath];
_puckArrow.fillColor = [_mapView.tintColor CGColor];
_puckArrow.bounds = CGRectMake(0, 0, MGLUserLocationAnnotationArrowSize, MGLUserLocationAnnotationArrowSize);
_puckArrow.position = CGPointMake(super.bounds.size.width / 2.0, super.bounds.size.height / 2.0);
_puckArrow.shouldRasterize = YES;
_puckArrow.rasterizationScale = [UIScreen mainScreen].scale;
_puckArrow.drawsAsynchronously = YES;
[self.layer addSublayer:_puckArrow];
}
if ( ! _puckModeActivated)
{
_puckModeActivated = YES;
[self updateFaux3DEffect];
}
}
- (UIBezierPath *)puckArrow
{
CGFloat max = MGLUserLocationAnnotationArrowSize;
UIBezierPath *bezierPath = UIBezierPath.bezierPath;
[bezierPath moveToPoint: CGPointMake(max * 0.5, 0)];
[bezierPath addLineToPoint: CGPointMake(max * 0.1, max)];
[bezierPath addLineToPoint: CGPointMake(max * 0.5, max * 0.65)];
[bezierPath addLineToPoint: CGPointMake(max * 0.9, max)];
[bezierPath addLineToPoint: CGPointMake(max * 0.5, 0)];
[bezierPath closePath];
return bezierPath;
}
- (void)drawDot
{
if (_puckModeActivated)
{
self.layer.sublayers = nil;
_puckDot = nil;
_puckArrow = nil;
}
BOOL showHeadingIndicator = _mapView.userTrackingMode == MGLUserTrackingModeFollowWithHeading;
// update heading indicator
//
if (showHeadingIndicator)
{
_headingIndicatorLayer.hidden = NO;
// heading indicator (tinted, semi-circle)
//
if ( ! _headingIndicatorLayer && self.annotation.heading.headingAccuracy)
{
CGFloat headingIndicatorSize = MGLUserLocationAnnotationHaloSize;
_headingIndicatorLayer = [CALayer layer];
_headingIndicatorLayer.bounds = CGRectMake(0, 0, headingIndicatorSize, headingIndicatorSize);
_headingIndicatorLayer.position = CGPointMake(super.bounds.size.width / 2.0, super.bounds.size.height / 2.0);
_headingIndicatorLayer.contents = (__bridge id)[[self headingIndicatorTintedGradientImage] CGImage];
_headingIndicatorLayer.contentsGravity = kCAGravityBottom;
_headingIndicatorLayer.contentsScale = [UIScreen mainScreen].scale;
_headingIndicatorLayer.opacity = 0.4;
_headingIndicatorLayer.shouldRasterize = YES;
_headingIndicatorLayer.rasterizationScale = [UIScreen mainScreen].scale;
_headingIndicatorLayer.drawsAsynchronously = YES;
[self.layer insertSublayer:_headingIndicatorLayer below:_dotBorderLayer];
}
// heading indicator accuracy mask (fan-shaped)
//
if ( ! _headingIndicatorMaskLayer && self.annotation.heading.headingAccuracy)
{
_headingIndicatorMaskLayer = [CAShapeLayer layer];
_headingIndicatorMaskLayer.frame = _headingIndicatorLayer.bounds;
_headingIndicatorMaskLayer.path = [[self headingIndicatorClippingMask] CGPath];
// apply the mask to the halo-radius-sized gradient layer
_headingIndicatorLayer.mask = _headingIndicatorMaskLayer;
_oldHeadingAccuracy = self.annotation.heading.headingAccuracy;
}
else if (_oldHeadingAccuracy != self.annotation.heading.headingAccuracy)
{
// recalculate the clipping mask based on updated accuracy
_headingIndicatorMaskLayer.path = [[self headingIndicatorClippingMask] CGPath];
_oldHeadingAccuracy = self.annotation.heading.headingAccuracy;
}
}
else
{
[_headingIndicatorLayer removeFromSuperlayer];
[_headingIndicatorMaskLayer removeFromSuperlayer];
_headingIndicatorLayer = nil;
_headingIndicatorMaskLayer = nil;
}
// update accuracy ring (if zoom or horizontal accuracy have changed)
//
if (_accuracyRingLayer && (_oldZoom != self.mapView.zoomLevel || _oldHorizontalAccuracy != self.annotation.location.horizontalAccuracy))
{
CGFloat accuracyRingSize = [self calculateAccuracyRingSize];
// only show the accuracy ring if it won't be obscured by the location dot
if (accuracyRingSize > MGLUserLocationAnnotationDotSize + 15)
{
_accuracyRingLayer.hidden = NO;
_accuracyRingLayer.bounds = CGRectMake(0, 0, accuracyRingSize, accuracyRingSize);
_accuracyRingLayer.cornerRadius = accuracyRingSize / 2;
// match the halo to the accuracy ring
_haloLayer.bounds = _accuracyRingLayer.bounds;
_haloLayer.cornerRadius = _accuracyRingLayer.cornerRadius;
_haloLayer.shouldRasterize = NO;
}
else
{
_accuracyRingLayer.hidden = YES;
_haloLayer.bounds = CGRectMake(0, 0, MGLUserLocationAnnotationHaloSize, MGLUserLocationAnnotationHaloSize);
_haloLayer.cornerRadius = MGLUserLocationAnnotationHaloSize / 2.0;
_haloLayer.shouldRasterize = YES;
_haloLayer.rasterizationScale = [UIScreen mainScreen].scale;
}
// store accuracy and zoom so we're not redrawing unchanged location updates
_oldHorizontalAccuracy = self.annotation.location.horizontalAccuracy;
_oldZoom = self.mapView.zoomLevel;
}
// accuracy ring (circular, tinted, mostly-transparent)
//
if ( ! _accuracyRingLayer && self.annotation.location.horizontalAccuracy)
{
CGFloat accuracyRingSize = [self calculateAccuracyRingSize];
_accuracyRingLayer = [self circleLayerWithSize:accuracyRingSize];
_accuracyRingLayer.backgroundColor = [_mapView.tintColor CGColor];
_accuracyRingLayer.opacity = 0.1;
_accuracyRingLayer.shouldRasterize = NO;
_accuracyRingLayer.allowsGroupOpacity = NO;
[self.layer addSublayer:_accuracyRingLayer];
}
// expanding sonar-like pulse (circular, tinted, fades out)
//
if ( ! _haloLayer)
{
_haloLayer = [self circleLayerWithSize:MGLUserLocationAnnotationHaloSize];
_haloLayer.backgroundColor = [_mapView.tintColor CGColor];
_haloLayer.allowsGroupOpacity = NO;
_haloLayer.zPosition = -0.1f;
// set defaults for the animations
CAAnimationGroup *animationGroup = [self loopingAnimationGroupWithDuration:3.0];
// scale out radially with initial acceleration
CAKeyframeAnimation *boundsAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale.xy"];
boundsAnimation.values = @[@0, @0.35, @1];
boundsAnimation.keyTimes = @[@0, @0.2, @1];
// go transparent as scaled out, start semi-opaque
CAKeyframeAnimation *opacityAnimation = [CAKeyframeAnimation animationWithKeyPath:@"opacity"];
opacityAnimation.values = @[@0.4, @0.4, @0];
opacityAnimation.keyTimes = @[@0, @0.2, @1];
animationGroup.animations = @[boundsAnimation, opacityAnimation];
[_haloLayer addAnimation:animationGroup forKey:@"animateTransformAndOpacity"];
[self.layer addSublayer:_haloLayer];
}
// background dot (white with black shadow)
//
if ( ! _dotBorderLayer)
{
_dotBorderLayer = [self circleLayerWithSize:MGLUserLocationAnnotationDotSize];
_dotBorderLayer.backgroundColor = [[UIColor whiteColor] CGColor];
_dotBorderLayer.shadowColor = [[UIColor blackColor] CGColor];
_dotBorderLayer.shadowOpacity = 0.25;
if (self.mapView.camera.pitch)
{
[self updateFaux3DEffect];
}
else
{
_dotBorderLayer.shadowOffset = CGSizeMake(0, 0);
_dotBorderLayer.shadowRadius = 3;
}
[self.layer addSublayer:_dotBorderLayer];
}
// inner dot (pulsing, tinted)
//
if ( ! _dotLayer)
{
_dotLayer = [self circleLayerWithSize:MGLUserLocationAnnotationDotSize * 0.75];
_dotLayer.backgroundColor = [_mapView.tintColor CGColor];
_dotLayer.shouldRasterize = NO;
// set defaults for the animations
CAAnimationGroup *animationGroup = [self loopingAnimationGroupWithDuration:1.5];
animationGroup.autoreverses = YES;
animationGroup.fillMode = kCAFillModeBoth;
// scale the dot up and down
CABasicAnimation *pulseAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale.xy"];
pulseAnimation.fromValue = @0.8;
pulseAnimation.toValue = @1;
// fade opacity in and out, subtly
CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
opacityAnimation.fromValue = @0.8;
opacityAnimation.toValue = @1;
animationGroup.animations = @[pulseAnimation, opacityAnimation];
[_dotLayer addAnimation:animationGroup forKey:@"animateTransformAndOpacity"];
[self.layer addSublayer:_dotLayer];
}
if (_puckModeActivated)
{
_puckModeActivated = NO;
[self updateFaux3DEffect];
}
}
- (CALayer *)circleLayerWithSize:(CGFloat)layerSize
{
CALayer *circleLayer = [CALayer layer];
circleLayer.bounds = CGRectMake(0, 0, layerSize, layerSize);
circleLayer.position = CGPointMake(super.bounds.size.width / 2.0, super.bounds.size.height / 2.0);
circleLayer.cornerRadius = layerSize / 2.0;
circleLayer.shouldRasterize = YES;
circleLayer.rasterizationScale = [UIScreen mainScreen].scale;
circleLayer.drawsAsynchronously = YES;
return circleLayer;
}
- (CAAnimationGroup *)loopingAnimationGroupWithDuration:(CGFloat)animationDuration
{
CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
animationGroup.duration = animationDuration;
animationGroup.repeatCount = INFINITY;
animationGroup.removedOnCompletion = NO;
animationGroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
return animationGroup;
}
- (CGFloat)calculateAccuracyRingSize
{
CGFloat latRadians = self.annotation.coordinate.latitude * M_PI / 180.0f;
CGFloat pixelRadius = self.annotation.location.horizontalAccuracy / cos(latRadians) / [self.mapView metersPerPixelAtLatitude:self.annotation.coordinate.latitude];
return pixelRadius * 2;
}
- (UIImage *)headingIndicatorTintedGradientImage
{
UIImage *image;
CGFloat haloRadius = MGLUserLocationAnnotationHaloSize / 2.0;
UIGraphicsBeginImageContextWithOptions(CGSizeMake(MGLUserLocationAnnotationHaloSize, haloRadius), NO, 0);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = UIGraphicsGetCurrentContext();
// gradient from the tint color to no-alpha tint color
CGFloat gradientLocations[] = {0.0, 1.0};
CGGradientRef gradient = CGGradientCreateWithColors(
colorSpace, (__bridge CFArrayRef)@[(id)[_mapView.tintColor CGColor],
(id)[[_mapView.tintColor colorWithAlphaComponent:0] CGColor]], gradientLocations);
// draw the gradient from the center point to the edge (full halo radius)
CGPoint centerPoint = CGPointMake(haloRadius, haloRadius);
CGContextDrawRadialGradient(context, gradient,
centerPoint, 0.0,
centerPoint, haloRadius,
nil);
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);
return image;
}
- (UIBezierPath *)headingIndicatorClippingMask
{
CGFloat accuracy = self.annotation.heading.headingAccuracy;
// size the mask using exagerated accuracy, but keep within a good display range
CGFloat clippingDegrees = 90 - (accuracy * 1.5);
clippingDegrees = fmin(clippingDegrees, 55);
clippingDegrees = fmax(clippingDegrees, 10);
CGRect ovalRect = CGRectMake(0, 0, MGLUserLocationAnnotationHaloSize, MGLUserLocationAnnotationHaloSize);
UIBezierPath *ovalPath = UIBezierPath.bezierPath;
// clip the oval to ± incoming accuracy degrees (converted to radians), from the top
[ovalPath addArcWithCenter:CGPointMake(CGRectGetMidX(ovalRect), CGRectGetMidY(ovalRect))
radius:CGRectGetWidth(ovalRect) / 2.0
startAngle:(-180 + clippingDegrees) * M_PI / 180
endAngle:-clippingDegrees * M_PI / 180
clockwise:YES];
[ovalPath addLineToPoint:CGPointMake(CGRectGetMidX(ovalRect), CGRectGetMidY(ovalRect))];
[ovalPath closePath];
return ovalPath;
}
@end

View File

@@ -0,0 +1,19 @@
#import "MGLUserLocation.h"
#import <CoreLocation/CoreLocation.h>
@class MGLMapView;
NS_ASSUME_NONNULL_BEGIN
@interface MGLUserLocation (Private)
@property (nonatomic, weak) MGLMapView *mapView;
@property (nonatomic, readwrite, nullable) CLLocation *location;
@property (nonatomic, readwrite, nullable) CLHeading *heading;
- (instancetype)initWithMapView:(MGLMapView *)mapView;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,15 @@
#import <Foundation/Foundation.h>
#import "MGLTypes.h"
NS_ASSUME_NONNULL_BEGIN
void mgl_linkBundleCategory();
@interface NSBundle (MGLAdditions)
+ (NSString *)mgl_resourceBundlePath;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,31 @@
#import "NSBundle+MGLAdditions.h"
#import "MGLMapView.h"
@implementation NSBundle (MGLAdditions)
void mgl_linkBundleCategory(){}
+ (NSString *)mgl_resourceBundlePath
{
NSString *resourceBundlePath = nil;
// check for resource bundle in framework bundle (Fabric, premade framework)
//
NSString *frameworkBundlePath = [NSString stringWithFormat:@"%@/Mapbox.framework/Mapbox.bundle",
[[NSBundle mainBundle] privateFrameworksPath]];
if ([NSBundle bundleWithPath:frameworkBundlePath]) resourceBundlePath = frameworkBundlePath;
// check for resource bundle in app bundle (static library)
//
if ( ! resourceBundlePath) resourceBundlePath = [[NSBundle bundleForClass:
[MGLMapView class]] pathForResource:@"Mapbox" ofType:@"bundle"];
// fall back to resources directly in app bundle (test app)
//
if ( ! resourceBundlePath) resourceBundlePath = [[NSBundle mainBundle] bundlePath];
return resourceBundlePath;
}
@end

View File

@@ -0,0 +1,9 @@
#import <Foundation/Foundation.h>
void mgl_linkProcessCategory();
@interface NSProcessInfo (MGLAdditions)
- (BOOL)mgl_isInterfaceBuilderDesignablesAgent;
@end

View File

@@ -0,0 +1,12 @@
#import "NSProcessInfo+MGLAdditions.h"
@implementation NSProcessInfo (MGLAdditions)
void mgl_linkProcessCategory(){}
- (BOOL)mgl_isInterfaceBuilderDesignablesAgent
{
return [self.processName isEqualToString:@"IBDesignablesAgentCocoaTouch"];
}
@end