forked from OneBusAway/onebusaway-iphone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOBAApplicationDelegate.m
424 lines (328 loc) · 17.1 KB
/
OBAApplicationDelegate.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
/**
* Copyright (C) 2009 bdferris <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import <SystemConfiguration/SystemConfiguration.h>
#import "OBAApplicationDelegate.h"
#import "OBANavigationTargetAware.h"
#import "OBALogger.h"
#import "OBASearchResultsMapViewController.h"
#import "OBARecentStopsViewController.h"
#import "OBABookmarksViewController.h"
#import "OBAInfoViewController.h"
#import "OBASearchController.h"
#import "OBAStopViewController.h"
#import "OBAStopIconFactory.h"
#import "OBAUserPreferencesMigration.h"
#import "OBARegionListViewController.h"
#import "OBARegionHelper.h"
#import "OBAReleaseNotesManager.h"
#import "OBAAnalytics.h"
static NSString * kOBAHiddenPreferenceUserId = @"OBAApplicationUserId";
static NSString * kOBASelectedTabIndexDefaultsKey = @"OBASelectedTabIndexDefaultsKey";
static NSString * kOBAShowExperimentalRegionsDefaultsKey = @"kOBAShowExperimentalRegionsDefaultsKey";
static NSString * kOBADefaultRegionApiServerName = @"regions.onebusaway.org";
static NSString *const kTrackingId = @"UA-2423527-17";
static NSString *const kAllowTracking = @"allowTracking";
@interface OBAApplicationDelegate ()
@property(nonatomic,readwrite) BOOL active;
@property(nonatomic) OBARegionHelper *regionHelper;
- (void) _constructUI;
- (void) _navigateToTargetInternal:(OBANavigationTarget*)navigationTarget;
- (void) _setNavigationTarget:(OBANavigationTarget*)target forViewController:(UIViewController*)viewController;
- (UIViewController*) _getViewControllerForTarget:(OBANavigationTarget*)target;
- (NSString *)userIdFromDefaults:(NSUserDefaults*)userDefaults;
- (void) _migrateUserPreferences;
- (NSString *)applicationDocumentsDirectory;
- (void)_updateSelectedTabIndex;
@end
@implementation OBAApplicationDelegate
- (id)init {
self = [super init];
if (self) {
self.active = NO;
_references = [[OBAReferencesV2 alloc] init];
_modelDao = [[OBAModelDAO alloc] init];
_locationManager = [[OBALocationManager alloc] initWithModelDao:_modelDao];
_modelService = [[OBAModelService alloc] init];
_modelService.references = _references;
_modelService.modelDao = _modelDao;
OBAModelFactory * modelFactory = [[OBAModelFactory alloc] initWithReferences:_references];
_modelService.modelFactory = modelFactory;
_modelService.locationManager = _locationManager;
_stopIconFactory = [[OBAStopIconFactory alloc] init];
[self refreshSettings];
}
return self;
}
- (void) navigateToTarget:(OBANavigationTarget*)navigationTarget {
[self performSelector:@selector(_navigateToTargetInternal:) withObject:navigationTarget afterDelay:0];
}
- (void)refreshSettings {
NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
NSString * apiServerName = nil;
if([self.modelDao.readCustomApiUrl isEqualToString:@""]) {
if (_modelDao.region != nil) {
apiServerName = [NSString stringWithFormat:@"%@", _modelDao.region.obaBaseUrl];
// remove the last '/'
apiServerName = [apiServerName substringToIndex:[apiServerName length]-1];
}
else {
self.regionHelper = [[OBARegionHelper alloc] init];
[self.modelDao writeSetRegionAutomatically:YES];
[self.regionHelper updateNearestRegion];
apiServerName = [NSString stringWithFormat:@"http://%@",apiServerName];
}
} else {
apiServerName = [NSString stringWithFormat:@"http://%@",self.modelDao.readCustomApiUrl];
if ([apiServerName hasSuffix:@"/"]) {
apiServerName = [apiServerName substringToIndex:[apiServerName length]-1];
}
}
NSString * userId = [self userIdFromDefaults:userDefaults];
NSString * appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
NSString * obaArgs = [NSString stringWithFormat:@"key=org.onebusaway.iphone&app_uid=%@&app_ver=%@",userId,appVersion];
OBADataSourceConfig * obaDataSourceConfig = [[OBADataSourceConfig alloc] initWithUrl:apiServerName args:obaArgs];
OBAJsonDataSource * obaJsonDataSource = [[OBAJsonDataSource alloc] initWithConfig:obaDataSourceConfig];
_modelService.obaJsonDataSource = obaJsonDataSource;
OBADataSourceConfig * googleMapsDataSourceConfig = [[OBADataSourceConfig alloc] initWithUrl:@"https://maps.googleapis.com" args:@"&sensor=true"];
OBAJsonDataSource * googleMapsJsonDataSource = [[OBAJsonDataSource alloc] initWithConfig:googleMapsDataSourceConfig];
_modelService.googleMapsJsonDataSource = googleMapsJsonDataSource;
NSString * regionApiServerName = [userDefaults objectForKey:@"oba_region_api_server"];
if (regionApiServerName == nil || [regionApiServerName length] == 0) {
regionApiServerName = kOBADefaultRegionApiServerName;
}
regionApiServerName = [NSString stringWithFormat:@"http://%@", regionApiServerName];
OBADataSourceConfig * obaRegionDataSourceConfig = [[OBADataSourceConfig alloc] initWithUrl:regionApiServerName args:obaArgs];
OBAJsonDataSource * obaRegionJsonDataSource = [[OBAJsonDataSource alloc] initWithConfig:obaRegionDataSourceConfig];
_modelService.obaRegionJsonDataSource = obaRegionJsonDataSource;
[userDefaults setObject:appVersion forKey:@"oba_application_version"];
}
- (void)_constructUI
{
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.window.backgroundColor = [UIColor blackColor];
self.tabBarController = [[UITabBarController alloc] init];
self.mapViewController = [[OBASearchResultsMapViewController alloc] init];
self.mapViewController.appDelegate = self;
self.mapNavigationController = [[UINavigationController alloc] initWithRootViewController:self.mapViewController];
self.recentsViewController = [[OBARecentStopsViewController alloc] init];
self.recentsViewController.appDelegate = self;
self.recentsNavigationController = [[UINavigationController alloc] initWithRootViewController:self.recentsViewController];
self.bookmarksViewController = [[OBABookmarksViewController alloc] init];
self.bookmarksViewController.appDelegate = self;
self.bookmarksNavigationController = [[UINavigationController alloc] initWithRootViewController:self.bookmarksViewController];
self.infoViewController = [[OBAInfoViewController alloc] init];
self.infoNavigationController = [[UINavigationController alloc] initWithRootViewController:self.infoViewController];
self.tabBarController.viewControllers = @[self.mapNavigationController, self.recentsNavigationController, self.bookmarksNavigationController, self.infoNavigationController];
self.tabBarController.delegate = self;
[self _updateSelectedTabIndex];
UIColor *tintColor = OBAGREEN;
[[UINavigationBar appearance] setTintColor:tintColor];
[[UISearchBar appearance] setTintColor:tintColor];
[[UISegmentedControl appearance] setTintColor:tintColor];
[[UITabBar appearance] setSelectedImageTintColor:tintColor];
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
[[UITabBar appearance] setTintColor:tintColor];
[[UITextField appearance] setTintColor:tintColor];
[[UISegmentedControl appearance] setTitleTextAttributes:@{UITextAttributeTextColor: [UIColor whiteColor]} forState:UIControlStateNormal];
[[UISegmentedControl appearance] setTitleTextAttributes:@{UITextAttributeTextColor: [UIColor whiteColor]} forState:UIControlStateSelected];
}
self.window.rootViewController = self.tabBarController;
if ([self.modelDao.readCustomApiUrl isEqualToString:@""]) {
_regionHelper = [[OBARegionHelper alloc] init];
if (self.modelDao.readSetRegionAutomatically && self.locationManager.locationServicesEnabled) {
[_regionHelper updateNearestRegion];
} else {
[_regionHelper updateRegion];
}
}
[self.window makeKeyAndVisible];
if ([OBAReleaseNotesManager shouldShowReleaseNotes]) {
[OBAReleaseNotesManager showReleaseNotes:self.window];
}
}
#pragma mark UIApplicationDelegate Methods
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//setup Google Analytics
NSDictionary *appDefaults = @{kAllowTracking: @(YES)};
[[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
// User must be able to opt out of tracking
[GAI sharedInstance].optOut = ![[NSUserDefaults standardUserDefaults] boolForKey:kAllowTracking];
[GAI sharedInstance].trackUncaughtExceptions = YES;
[[[GAI sharedInstance] logger] setLogLevel:kGAILogLevelVerbose];
//don't report to Google Analytics when developing
#ifdef DEBUG
[[GAI sharedInstance] setDryRun:YES];
#endif
self.tracker = [[GAI sharedInstance] trackerWithTrackingId:kTrackingId];
[self _migrateUserPreferences];
[self _constructUI];
return YES;
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
CLLocation * location = _locationManager.currentLocation;
if ( location )
{
_modelDao.mostRecentLocation = location;
}
}
- (void)applicationWillTerminate:(UIApplication *)application {
[self applicationDidEnterBackground:application]; // call for iOS < 4.0 devices
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
self.active = YES;
self.tabBarController.selectedIndex = [[NSUserDefaults standardUserDefaults] integerForKey:kOBASelectedTabIndexDefaultsKey];
[GAI sharedInstance].optOut =
![[NSUserDefaults standardUserDefaults] boolForKey:kAllowTracking];
}
- (void)applicationWillResignActive:(UIApplication *)application {
if([self.modelDao.readCustomApiUrl isEqualToString:@""]) {
[OBAAnalytics reportEventWithCategory:@"app_settings" action:@"configured_region" label:[NSString stringWithFormat:@"API Region: %@",self.modelDao.region.regionName] value:nil];
}else{
[OBAAnalytics reportEventWithCategory:@"app_settings" action:@"configured_region" label:@"API Region: Custom URL" value:nil];
}
[OBAAnalytics reportEventWithCategory:@"app_settings" action:@"general" label:[NSString stringWithFormat:@"Set Region Automatically: %@", (self.modelDao.readSetRegionAutomatically ? @"YES" : @"NO")] value:nil];
BOOL _showExperimentalRegions = NO;
if ([[NSUserDefaults standardUserDefaults] boolForKey: @"kOBAShowExperimentalRegionsDefaultsKey"])
_showExperimentalRegions = [[NSUserDefaults standardUserDefaults] boolForKey: @"kOBAShowExperimentalRegionsDefaultsKey"];
[OBAAnalytics reportEventWithCategory:@"app_settings" action:@"general" label:[NSString stringWithFormat:@"Show Experimental Regions: %@", (_showExperimentalRegions ? @"YES" : @"NO")] value:nil];
self.active = NO;
}
#pragma mark - UITabBarControllerDelegate
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
NSUInteger oldIndex = [self.tabBarController.viewControllers indexOfObject:[self.tabBarController selectedViewController]];
NSUInteger newIndex = [self.tabBarController.viewControllers indexOfObject:viewController];
if(newIndex == 0 && newIndex == oldIndex) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"OBAMapButtonRecenterNotification" object:nil];
}
return YES;
}
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
[[NSUserDefaults standardUserDefaults] setInteger:tabBarController.selectedIndex forKey:kOBASelectedTabIndexDefaultsKey];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)_updateSelectedTabIndex {
NSInteger selectedIndex = 0;
NSString * startupView = nil;
if ([[NSUserDefaults standardUserDefaults] objectForKey:kOBASelectedTabIndexDefaultsKey]) {
selectedIndex = [[NSUserDefaults standardUserDefaults] integerForKey:kOBASelectedTabIndexDefaultsKey];
}
self.tabBarController.selectedIndex = selectedIndex;
switch (selectedIndex) {
case 0:
startupView = @"OBASearchResultsMapViewController";
break;
case 1:
startupView = @"OBARecentStopsViewController";
break;
case 2:
startupView = @"OBABookmarksViewController";
break;
case 3:
startupView = @"OBAInfoViewController";
break;
default:
startupView = @"Unknown";
break;
}
[OBAAnalytics reportEventWithCategory:@"app_settings" action:@"startup" label:[NSString stringWithFormat:@"Startup View: %@",startupView] value:nil];
}
- (void) _navigateToTargetInternal:(OBANavigationTarget*)navigationTarget {
[_references clear];
[self.mapNavigationController popToRootViewControllerAnimated:NO];
if (OBANavigationTargetTypeSearchResults == navigationTarget.target) {
[self.tabBarController setSelectedViewController:self.mapNavigationController];
self.mapViewController.navigationTarget = navigationTarget;
}
else if (OBANavigationTargetTypeContactUs == navigationTarget.target) {
[self.tabBarController setSelectedViewController:self.infoNavigationController];
[self.infoViewController openContactUs];
}
else if (OBANavigationTargetTypeSettings == navigationTarget.target) {
[self.tabBarController setSelectedViewController:self.infoNavigationController];
[self.infoViewController openSettings];
}
else if (OBANavigationTargetTypeAgencies == navigationTarget.target) {
[self.tabBarController setSelectedViewController:self.infoNavigationController];
[self.infoViewController openAgencies];
}
else if (OBANavigationTargetTypeBookmarks == navigationTarget.target) {
[self.tabBarController setSelectedViewController:self.bookmarksNavigationController];
}
else {
NSLog(@"Unhandled target in %s: %d", __PRETTY_FUNCTION__, navigationTarget.target);
}
}
- (void) _setNavigationTarget:(OBANavigationTarget*)target forViewController:(UIViewController*)viewController {
if( ! [viewController conformsToProtocol:@protocol(OBANavigationTargetAware) ] )
return;
if( ! [viewController respondsToSelector:@selector(setNavigationTarget:) ] )
return;
id<OBANavigationTargetAware> targetAware = (id<OBANavigationTargetAware>) viewController;
[targetAware setNavigationTarget:target];
}
- (UIViewController*) _getViewControllerForTarget:(OBANavigationTarget*)target {
switch (target.target) {
case OBANavigationTargetTypeStop:
return [[OBAStopViewController alloc] initWithApplicationDelegate:self];
default:
return nil;
}
}
- (NSString *)userIdFromDefaults:(NSUserDefaults*)userDefaults {
NSString * userId = [userDefaults stringForKey:kOBAHiddenPreferenceUserId];
if( ! userId) {
CFUUIDRef theUUID = CFUUIDCreate(kCFAllocatorDefault);
if (theUUID) {
userId = CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, theUUID));
CFRelease(theUUID);
[userDefaults setObject:userId forKey:kOBAHiddenPreferenceUserId];
[userDefaults synchronize];
}
else {
userId = @"anonymous";
}
}
return userId;
}
- (void) _migrateUserPreferences {
OBAUserPreferencesMigration * migration = [[OBAUserPreferencesMigration alloc] init];
NSString * path = [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"OneBusAway.sqlite"];
[migration migrateCoreDataPath:path toDao:_modelDao];
}
- (void)regionSelected {
[_regionNavigationController removeFromParentViewController];
_regionNavigationController = nil;
_regionListViewController = nil;
[self refreshSettings];
self.window.rootViewController = self.tabBarController;
[_window makeKeyAndVisible];
}
- (void) showRegionListViewController
{
_regionListViewController = [[OBARegionListViewController alloc] initWithApplicationDelegate:self];
_regionNavigationController = [[UINavigationController alloc] initWithRootViewController:_regionListViewController];
self.window.rootViewController = _regionNavigationController;
}
#pragma mark - Application's documents directory
/**
* Returns the path to the application's documents directory.
*/
- (NSString *)applicationDocumentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? paths[0] : nil;
return basePath;
}
@end