This repository was archived by the owner on Apr 16, 2025. It is now read-only.
forked from pschmied/CycleTracks
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathCycleAtlantaAppDelegate.m
More file actions
471 lines (379 loc) · 18.4 KB
/
CycleAtlantaAppDelegate.m
File metadata and controls
471 lines (379 loc) · 18.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
/** Cycle Atlanta, Copyright 2012, 2013 Georgia Institute of Technology
* Atlanta, GA. USA
*
* @author Christopher Le Dantec <ledantec@gatech.edu>
* @author Anhong Guo <guoanhong@gatech.edu>
*
* Updated/Modified for Atlanta's app deployment. Based on the
* CycleTracks codebase for SFCTA.
*
** CycleTracks, Copyright 2009,2010 San Francisco County Transportation Authority
* San Francisco, CA, USA
*
* @author Matt Paul <mattpaul@mopimp.com>
*
* This file is part of CycleTracks.
*
* CycleTracks is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CycleTracks is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CycleTracks. If not, see <http://www.gnu.org/licenses/>.
*/
//
// CycleTracksAppDelegate.m
// CycleTracks
//
// Copyright 2009-2010 SFCTA. All rights reserved.
// Written by Matt Paul <mattpaul@mopimp.com> on 9/21/09.
// For more information on the project,
// e-mail Billy Charlton at the SFCTA <billy.charlton@sfcta.org>
#import <CommonCrypto/CommonDigest.h>
#import "CycleAtlantaAppDelegate.h"
//#import "PersonalInfoViewController.h"
#import "Cycle_Atlanta-Swift.h"
#import "RecordTripViewController.h"
#import "SavedTripsViewController.h"
#import "SavedNotesViewController.h"
#import "TripManager.h"
#import "NSString+MD5Addition.h"
#import "UIDevice+IdentifierAddition.h"
#import "constants.h"
#import "DetailViewController.h"
#import "NoteManager.h"
#import <CoreData/NSMappingModel.h>
#import "ProgressView.h"
#import "OBAApplication.h"
#define SYSTEM_VERSION_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)
@implementation CycleAtlantaAppDelegate
@synthesize window;
@synthesize tabBarController;
@synthesize uniqueIDHash;
@synthesize isRecording;
@synthesize locationManager;
@synthesize storeLoadingView;
@synthesize managedObjectContext;
#pragma mark -
#pragma mark Application lifecycle
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
// init our unique ID hash
/*
[self initUniqueIDHash];
self.storeLoadingView = [ProgressView progressViewInView: self.storeLoadingView messageString:nil progressTypePlain:NO] ;
[window addSubview:self.storeLoadingView];
[window makeKeyAndVisible];
[self performSelectorInBackground:@selector(loadPersistentStore) withObject:nil];
*/
}
- (id)init {
self = [super init];
if (self) {
[[OBAApplication sharedApplication] start];
self.regionHelper = [[OBARegionHelper alloc] init];
[self.regionHelper updateNearestRegion];
}
return self;
}
- (void) showRegionSelectMessage {
UIAlertController* alert = [UIAlertController
alertControllerWithTitle:@"Alert"
message:@"Region couldn't be found. Please select a region from settings."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction
actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainWindow" bundle:nil];
PersonalInfoViewController *myVC = (PersonalInfoViewController *)[storyboard instantiateViewControllerWithIdentifier:@"personalInfo"];
[myVC setHideViews];
[self.window.rootViewController presentViewController:myVC animated:YES completion:nil];
}];
[alert addAction:defaultAction];
[self.window.rootViewController presentViewController:alert animated:YES completion:nil];
}
-(void)loadPersistentStore
{
NSLog(@"loadPersistentStore!");
NSPersistentStoreCoordinator* coordinator = [self persistentStoreCoordinator];
[self performSelectorOnMainThread:@selector(persistentStoreLoaded:) withObject:coordinator waitUntilDone:YES];
}
-(void)persistentStoreLoaded: (NSPersistentStoreCoordinator *) coordinator;
{
NSLog(@"persistentStoreLoaded.");
[self.storeLoadingView removeFromSuperview];
self.storeLoadingView = nil;
CGRect frame = [[UIScreen mainScreen] bounds];
backgroundView = [[UIView alloc] initWithFrame:frame];
backgroundView.backgroundColor = [UIColor colorWithRed:((float) 0 / 255.0f)
green:((float) 0 / 255.0f)
blue:((float) 0 / 255.0f)
alpha:1.0f];
NSLog(@"persistentStoreLoaded...Context ?");
NSManagedObjectContext *context = [self managedObjectContext: coordinator];
if (!context) {
NSLog(@"DEBUG: context error");
}
// TODO move in viewWillAppear ?
TripManager *tripManager = [[TripManager alloc] initWithManagedObjectContext:context];
NoteManager *noteManager = [[NoteManager alloc] initWithManagedObjectContext:context];
int nav_controller=1;
RecordTripViewController *recordVC;
if(nav_controller==1)
{
UINavigationController* uinav=[[((UITabBarController *) self.window.rootViewController) viewControllers] objectAtIndex:0];
recordVC=[uinav.viewControllers objectAtIndex:0];
}
else
{
//recordVC = [[((UITabBarController *) self.window.rootViewController) viewControllers] objectAtIndex:0];
}
[recordVC initTripManager:tripManager];
[recordVC initNoteManager:noteManager];
SavedTripsViewController *tripsVC = [[((UITabBarController *) self.window.rootViewController) viewControllers] objectAtIndex:1];
tripsVC.delegate = recordVC;
[tripsVC initTripManager:tripManager];
SavedNotesViewController *notesVC = [[((UITabBarController *) self.window.rootViewController) viewControllers] objectAtIndex:2];
[notesVC initNoteManager:noteManager];
// TODO: storyboard link to here
/*
UINavigationController *personalNav = (UINavigationController*)[tabBarController.viewControllers
objectAtIndex:3];
PersonalInfoViewController *personalVC = (PersonalInfoViewController *)[personalNav topViewController];
personalVC.managedObjectContext = context;
*/
}
- (void)initUniqueIDHash
{
//if (SYSTEM_VERSION_LESS_THAN(@"7.0")) {
self.uniqueIDHash = [[UIDevice currentDevice] uniqueGlobalDeviceIdentifier]; // save for later.
//}
//if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
// self.uniqueIDHash = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
// NSLog(@"iOS 7");
//}
NSLog(@"Hashed uniqueID: %@", uniqueIDHash);
}
/**
applicationWillTerminate: saves changes in the application's managed object context before the application terminates.
*/
- (void)applicationWillTerminate:(UIApplication *)application {
NSError *error = nil;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
*/
NSLog(@"applicationWillTerminate: Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
- (void)applicationDidEnterBackground:(UIApplication *) application
{
CycleAtlantaAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
if(appDelegate.isRecording){
NSLog(@"BACKGROUNDED and recording"); //set location service to startUpdatingLocation
[appDelegate.locationManager startUpdatingLocation];
} else {
NSLog(@"BACKGROUNDED and sitting idle"); //set location service to startMonitoringSignificantLocationChanges
[appDelegate.locationManager stopUpdatingLocation];
//[appDelegate.locationManager startMonitoringSignificantLocationChanges];
}
if([[NSUserDefaults standardUserDefaults] boolForKey:@"magnetometerIsOn"])
{
NSLog(@"BACKGROUNDED and keep watching magnetic field");
[appDelegate.locationManager startUpdatingHeading];
}
}
- (void)applicationDidBecomeActive:(UIApplication *) application
{
//always turnon location updating when active.
CycleAtlantaAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate.locationManager requestAlwaysAuthorization];
[appDelegate.locationManager startUpdatingLocation];
}
#pragma mark -
#pragma mark Core Data stack
/**
Returns the managed object context for the application.
If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
*/
- (NSManagedObjectContext *) managedObjectContext: (NSPersistentStoreCoordinator *) coordinator {
if (managedObjectContext != nil) {
return managedObjectContext;
}
//NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator: coordinator];
}
return managedObjectContext;
}
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel != nil) {
return managedObjectModel;
}
NSString *path = [[NSBundle mainBundle] pathForResource:@"CycleAtlanta" ofType:@"momd"];
NSURL *momURL = [NSURL fileURLWithPath:path];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:momURL];
return managedObjectModel;
}
/**
Returns the persistent store coordinator for the application.
If the coordinator doesn't already exist, it is created and the application's store added to it.
If it does exist, it tests for and then migrates the store as needed.
*/
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
NSError * error;
if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}
NSURL *storeURL;// = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"CycleTracks.sqlite"]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:
[[NSURL fileURLWithPath:[[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"CycleTracks.sqlite"]] path]] &&
[fileManager fileExistsAtPath:
[[NSURL fileURLWithPath:[[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"CycleAtlanta.sqlite"]] path]])
{
//both existprevious migration failed, start over.
if(![fileManager removeItemAtPath:[[NSURL fileURLWithPath:[[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"CycleAtlanta.sqlite"]] path]
error:&error])
{
NSLog(@"Remove file error %@", error );
}
storeURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"CycleTracks.sqlite"]];
}
else if ([fileManager fileExistsAtPath:
[[NSURL fileURLWithPath:[[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"CycleTracks.sqlite"]] path]])
{
//old version store exists, need to migrate
storeURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"CycleTracks.sqlite"]];
}
else
{
//use current name.
storeURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"CycleAtlanta.sqlite"]];
}
// migrate the store if needed, returns the migrated storeURL
storeURL = [self migratePersistentStore: storeURL];
// create the coordinator
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
//not the most sophisticated error handling
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return persistentStoreCoordinator;
}
- (NSURL *) migratePersistentStore: (NSURL *) sourceURL {
BOOL result;
NSError *error = nil;
NSDictionary *sourceMetadata = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:NSSQLiteStoreType
URL:sourceURL
error:&error];
if(!sourceMetadata )//assume first run, so break w/o migrating anything.
return sourceURL;
NSURL *destinationURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"CycleAtlanta.sqlite"]];
NSManagedObjectModel *destinationModel = [self managedObjectModel];
//do the migration. assuming one step here from previous to current model.
NSManagedObjectModel *sourceModel = [NSManagedObjectModel mergedModelFromBundles:nil
forStoreMetadata:sourceMetadata];
NSMigrationManager *migrationManager = [[NSMigrationManager alloc]
initWithSourceModel:sourceModel
destinationModel:destinationModel];
NSMappingModel *mappingModel = [NSMappingModel mappingModelFromBundles:nil
forSourceModel:sourceModel
destinationModel:destinationModel];
if (mappingModel == nil) {
NSLog(@"DEBUG no mapping model, no need to migrate.");
return destinationURL;
}
NSLog(@"DEBUG: start migration");
//request migration task continue if the app is backgrounded.
UIBackgroundTaskIdentifier taskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(void) {
// no-op. interrupted migration will simply start over next time.
}];
[self performSelectorOnMainThread:@selector(setUpgradeMessage) withObject:nil waitUntilDone:NO];
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
[migrationManager addObserver:self.storeLoadingView forKeyPath:@"migrationProgress" options:0 context:NULL];
result = [migrationManager migrateStoreFromURL:sourceURL
type:NSSQLiteStoreType
options:nil
withMappingModel:mappingModel
toDestinationURL:destinationURL
destinationType:NSSQLiteStoreType
destinationOptions:nil
error:&error];
NSLog(@"DEBUG: finish migration");
if (taskId != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:taskId];
}
[migrationManager removeObserver:self.storeLoadingView forKeyPath:@"migrationProgress" ];
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];
if(result)
{
//only remove the previous store if the migration succeeded.
NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager removeItemAtPath:[[NSURL fileURLWithPath:[[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"CycleTracks.sqlite"]] path]
error:&error])
{
NSLog(@"Remove file error %@", error );
}
}
else
{
destinationURL = nil;
}
return destinationURL;
}
- (void)setUpgradeMessage{
[self.storeLoadingView setVisible:TRUE messageString:kInitMessage ];
}
#pragma mark -
#pragma mark Application's Documents directory
/**
Returns the path to the application's Documents directory.
*/
- (NSString *) applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
- (void)writeSetRegionAutomatically:(BOOL)setRegionAutomatically {
[[OBAApplication sharedApplication].modelDao writeSetRegionAutomatically:setRegionAutomatically];
}
- (BOOL)readSetRegionAutomatically {
BOOL readSetRegionAuto = [OBAApplication sharedApplication].modelDao.readSetRegionAutomatically;
return readSetRegionAuto;
}
- (void)regionSelected {
// [_regionNavigationController removeFromParentViewController];
// _regionNavigationController = nil;
// _regionListViewController = nil;
//
// [[OBAApplication sharedApplication] refreshSettings];
//
// self.window.rootViewController = self.tabBarController;
// [_window makeKeyAndVisible];
}
- (void)showRegionListViewController {
// _regionListViewController = [[OBARegionListViewController alloc] init];
// _regionNavigationController = [[UINavigationController alloc] initWithRootViewController:_regionListViewController];
//
// self.window.rootViewController = _regionNavigationController;
}
#pragma mark -
#pragma mark Memory management
- (void)dealloc {
self.isRecording = nil;
}
@end