forked from merlos/iOS-Open-GPX-Tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathViewController.swift
1414 lines (1192 loc) · 63.7 KB
/
ViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// ViewController.swift
// OpenGpxTracker
//
// Created by merlos on 13/09/14.
//
// Localized by nitricware on 19/08/19.
//
import UIKit
import CoreLocation
import MapKit
import CoreGPX
/// Purple color for button background
let kPurpleButtonBackgroundColor: UIColor = UIColor(red: 146.0/255.0, green: 166.0/255.0, blue: 218.0/255.0, alpha: 0.90)
/// Green color for button background
let kGreenButtonBackgroundColor: UIColor = UIColor(red: 142.0/255.0, green: 224.0/255.0, blue: 102.0/255.0, alpha: 0.90)
/// Red color for button background
let kRedButtonBackgroundColor: UIColor = UIColor(red: 244.0/255.0, green: 94.0/255.0, blue: 94.0/255.0, alpha: 0.90)
/// Blue color for button background
let kBlueButtonBackgroundColor: UIColor = UIColor(red: 74.0/255.0, green: 144.0/255.0, blue: 226.0/255.0, alpha: 0.90)
/// Blue color for disabled button background
let kDisabledBlueButtonBackgroundColor: UIColor = UIColor(red: 74.0/255.0, green: 144.0/255.0, blue: 226.0/255.0, alpha: 0.10)
/// Red color for disabled button background
let kDisabledRedButtonBackgroundColor: UIColor = UIColor(red: 244.0/255.0, green: 94.0/255.0, blue: 94.0/255.0, alpha: 0.10)
/// White color for button background
let kWhiteBackgroundColor: UIColor = UIColor(red: 254.0/255.0, green: 254.0/255.0, blue: 254.0/255.0, alpha: 0.90)
/// Delete Waypoint Button tag. Used in a waypoint bubble
let kDeleteWaypointAccesoryButtonTag = 666
/// Edit Waypoint Button tag. Used in a waypoint bubble.
let kEditWaypointAccesoryButtonTag = 333
/// Text to display when the system is not providing coordinates.
let kNotGettingLocationText = NSLocalizedString("NO_LOCATION", comment: "no comment")
/// Text to display unknown accuracy
let kUnknownAccuracyText = "±···"
/// Text to display unknown speed.
let kUnknownSpeedText = "·.··"
/// Size for small buttons
let kButtonSmallSize: CGFloat = 48.0
/// Size for large buttons
let kButtonLargeSize: CGFloat = 96.0
/// Separation between buttons
let kButtonSeparation: CGFloat = 6.0
/// Upper limits threshold (in meters) on signal accuracy.
let kSignalAccuracy6 = 6.0
/// Upper limits threshold (in meters) on signal accuracy.
let kSignalAccuracy5 = 11.0
/// Upper limits threshold (in meters) on signal accuracy.
let kSignalAccuracy4 = 31.0
/// Upper limits threshold (in meters) on signal accuracy.
let kSignalAccuracy3 = 51.0
/// Upper limits threshold (in meters) on signal accuracy.
let kSignalAccuracy2 = 101.0
/// Upper limits threshold (in meters) on signal accuracy.
let kSignalAccuracy1 = 201.0
///
/// Main View Controller of the Application. It is loaded when the application is launched
///
/// Displays a map and a set the buttons to control the tracking
///
///
class ViewController: UIViewController, UIGestureRecognizerDelegate {
/// Shall the map be centered on current user position?
/// If yes, whenever the user moves, the center of the map too.
var followUser: Bool = true {
didSet {
if followUser {
print("followUser=true")
followUserButton.setImage(UIImage(named: "follow_user_high"), for: UIControl.State())
map.setCenter((map.userLocation.coordinate), animated: true)
} else {
print("followUser=false")
followUserButton.setImage(UIImage(named: "follow_user"), for: UIControl.State())
}
}
}
/// TBD (not currently used)
var followUserBeforePinchGesture = true
/// location manager instance configuration
let locationManager: CLLocationManager = {
let manager = CLLocationManager()
manager.requestAlwaysAuthorization()
manager.activityType = CLActivityType(rawValue: Preferences.shared.locationActivityTypeInt)!
print("Chosen CLActivityType: \(manager.activityType.name)")
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.distanceFilter = 2 //meters
manager.headingFilter = 3 //degrees (1 is default)
manager.pausesLocationUpdatesAutomatically = false
if #available(iOS 9.0, *) {
manager.allowsBackgroundLocationUpdates = true
}
return manager
}()
/// Map View
var map: GPXMapView
/// Map View delegate
let mapViewDelegate = MapViewDelegate()
/// Stop watch instance to control elapsed time
var stopWatch = StopWatch()
/// Name of the last file that was saved (without extension)
var lastGpxFilename: String = ""
/// Status variable that indicates if the app was sent to background.
var wasSentToBackground: Bool = false
/// Status variable that indicates if the location service auth was denied.
var isDisplayingLocationServicesDenied: Bool = false
/// Has the map any waypoint?
var hasWaypoints: Bool = false {
/// Whenever it is updated, if it has waypoints it sets the save and reset button
didSet {
if hasWaypoints {
saveButton.backgroundColor = kBlueButtonBackgroundColor
resetButton.backgroundColor = kRedButtonBackgroundColor
}
}
}
/// Defines the different statuses regarding tracking current user location.
enum GpxTrackingStatus {
/// Tracking has not started or map was reset
case notStarted
/// Tracking is ongoing
case tracking
/// Tracking is paused (the map has some contents)
case paused
}
/// Tells what is the current status of the Map Instance.
var gpxTrackingStatus: GpxTrackingStatus = GpxTrackingStatus.notStarted {
didSet {
print("gpxTrackingStatus changed to \(gpxTrackingStatus)")
switch gpxTrackingStatus {
case .notStarted:
print("switched to non started")
// set Tracker button to allow Start
trackerButton.setTitle(NSLocalizedString("START_TRACKING", comment: "no comment"), for: UIControl.State())
trackerButton.backgroundColor = kGreenButtonBackgroundColor
//save & reset button to transparent.
saveButton.backgroundColor = kDisabledBlueButtonBackgroundColor
resetButton.backgroundColor = kDisabledRedButtonBackgroundColor
//reset clock
stopWatch.reset()
timeLabel.text = stopWatch.elapsedTimeString
map.clearMap() //clear map
lastGpxFilename = "" //clear last filename, so when saving it appears an empty field
map.coreDataHelper.clearAll()
map.coreDataHelper.deleteCDRootFromCoreData()
totalTrackedDistanceLabel.distance = (map.session.totalTrackedDistance)
currentSegmentDistanceLabel.distance = (map.session.currentSegmentDistance)
/*
// XXX Left here for reference
UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in
self.trackerButton.hidden = true
self.pauseButton.hidden = false
}, completion: {(f: Bool) -> Void in
println("finished animation start tracking")
})
*/
case .tracking:
print("switched to tracking mode")
// set tracerkButton to allow Pause
trackerButton.setTitle(NSLocalizedString("PAUSE", comment: "no comment"), for: UIControl.State())
trackerButton.backgroundColor = kPurpleButtonBackgroundColor
//activate save & reset buttons
saveButton.backgroundColor = kBlueButtonBackgroundColor
resetButton.backgroundColor = kRedButtonBackgroundColor
// start clock
self.stopWatch.start()
case .paused:
print("switched to paused mode")
// set trackerButton to allow Resume
self.trackerButton.setTitle(NSLocalizedString("RESUME", comment: "no comment"), for: UIControl.State())
self.trackerButton.backgroundColor = kGreenButtonBackgroundColor
// activate save & reset (just in case switched from .NotStarted)
saveButton.backgroundColor = kBlueButtonBackgroundColor
resetButton.backgroundColor = kRedButtonBackgroundColor
//pause clock
self.stopWatch.stop()
// start new track segment
self.map.startNewTrackSegment()
}
}
}
/// Editing Waypoint Temporal Reference
var lastLocation: CLLocation? //Last point of current segment.
//UI
/// Label with the title of the app
var appTitleLabel: UILabel
/// Image with the GPS signal
var signalImageView: UIImageView
/// Current GPS signal accuracy text (based on kSignalAccuracyX constants)
var signalAccuracyLabel: UILabel
/// Label that displays current latitude and longitude (lat,long)
var coordsLabel: UILabel
/// Displays current elapsed time (00:00)
var timeLabel: UILabel
/// Label that displays last known speed (in km/h)
var speedLabel: UILabel
/// Distance of the total segments tracked
var totalTrackedDistanceLabel: DistanceLabel
/// Distance of the current segment being tracked (since last time the Tracker button was pressed)
var currentSegmentDistanceLabel: DistanceLabel
/// Used to display in imperial (foot, miles, mph) or metric system (m, km, km/h)
var useImperial = false
/// Follow user button (bottom bar)
var followUserButton: UIButton
/// New pin button (bottom bar)
var newPinButton: UIButton
/// View GPX Files button
var folderButton: UIButton
/// View app about button
var aboutButton: UIButton
/// View preferences button
var preferencesButton: UIButton
/// Share current gpx file button
var shareButton: UIButton
/// Spinning Activity Indicator for shareButton
let shareActivityIndicator: UIActivityIndicatorView
/// Spinning Activity Indicator's color
var shareActivityColor = UIColor(red: 0, green: 0.61, blue: 0.86, alpha: 1)
/// Reset map button (bottom bar)
var resetButton: UIButton
/// Start/Pause tracker button (bottom bar)
var trackerButton: UIButton
/// Save current track into a GPX file
var saveButton: UIButton
/// Check if device is notched type phone
var isIPhoneX = false
// Signal accuracy images
/// GPS signal image. Level 0 (no signal)
let signalImage0 = UIImage(named: "signal0")
/// GPS signal image. Level 1
let signalImage1 = UIImage(named: "signal1")
/// GPS signal image. Level 2
let signalImage2 = UIImage(named: "signal2")
/// GPS signal image. Level 3
let signalImage3 = UIImage(named: "signal3")
/// GPS signal image. Level 4
let signalImage4 = UIImage(named: "signal4")
/// GPS signal image. Level 5
let signalImage5 = UIImage(named: "signal5")
/// GPS signal image. Level 6
let signalImage6 = UIImage(named: "signal6")
/// Initializer. Just initializes the class vars/const
required init(coder aDecoder: NSCoder) {
self.map = GPXMapView(coder: aDecoder)!
self.appTitleLabel = UILabel(coder: aDecoder)!
self.signalImageView = UIImageView(coder: aDecoder)!
self.signalAccuracyLabel = UILabel(coder: aDecoder)!
self.coordsLabel = UILabel(coder: aDecoder)!
self.timeLabel = UILabel(coder: aDecoder)!
self.speedLabel = UILabel(coder: aDecoder)!
self.totalTrackedDistanceLabel = DistanceLabel(coder: aDecoder)!
self.currentSegmentDistanceLabel = DistanceLabel(coder: aDecoder)!
self.followUserButton = UIButton(coder: aDecoder)!
self.newPinButton = UIButton(coder: aDecoder)!
self.folderButton = UIButton(coder: aDecoder)!
self.resetButton = UIButton(coder: aDecoder)!
self.aboutButton = UIButton(coder: aDecoder)!
self.preferencesButton = UIButton(coder: aDecoder)!
self.shareButton = UIButton(coder: aDecoder)!
self.trackerButton = UIButton(coder: aDecoder)!
self.saveButton = UIButton(coder: aDecoder)!
self.shareActivityIndicator = UIActivityIndicatorView(coder: aDecoder)
super.init(coder: aDecoder)!
}
///
/// De initalize the ViewController.
///
/// Current implementation removes notification observers
///
deinit {
print("*** deinit")
removeNotificationObservers()
}
/// Handles status bar color as a result from iOS 13 appearance changes
override var preferredStatusBarStyle: UIStatusBarStyle {
if #available(iOS 13, *) {
if !isIPhoneX {
if self.traitCollection.userInterfaceStyle == .dark && map.tileServer == .apple {
self.view.backgroundColor = .black
return .lightContent
}
else {
self.view.backgroundColor = .white
return .darkContent
}
}
// > iPhone X has no opaque status bar
else {
// if is > iP X status bar can be white when map is dark
return map.tileServer == .apple ? .default : .darkContent
}
}
else { // < iOS 13
return .default
}
}
///
/// Initializes the view. It adds the UI elements to the view.
///
/// All the UI is built programatically on this method. Interface builder is not used.
///
override func viewDidLoad() {
super.viewDidLoad()
stopWatch.delegate = self
map.coreDataHelper.retrieveFromCoreData()
//Because of the edges, iPhone X* is slightly different on the layout.
//So, Is the current device an iPhone X?
if UIDevice().userInterfaceIdiom == .phone {
switch UIScreen.main.nativeBounds.height {
case 1136:
print("device: IPHONE 5,5S,5C")
case 1334:
print("device: IPHONE 6,7,8 IPHONE 6S,7S,8S ")
case 1920, 2208:
print("device: IPHONE 6PLUS, 6SPLUS, 7PLUS, 8PLUS")
case 2436:
print("device: IPHONE X, IPHONE XS")
isIPhoneX = true
case 2688:
print("device: IPHONE XS_MAX")
isIPhoneX = true
case 1792:
print("device: IPHONE XR")
isIPhoneX = true
default:
print("UNDETERMINED")
}
}
// Map autorotate configuration
map.autoresizesSubviews = true
map.autoresizingMask = [.flexibleHeight, .flexibleWidth]
self.view.autoresizesSubviews = true
self.view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
// Map configuration Stuff
map.delegate = mapViewDelegate
map.showsUserLocation = true
let mapH: CGFloat = self.view.bounds.size.height - (isIPhoneX ? 0.0 : 20.0)
map.frame = CGRect(x: 0.0, y: (isIPhoneX ? 0.0 : 20.0), width: self.view.bounds.size.width, height: mapH)
map.isZoomEnabled = true
map.isRotateEnabled = true
//set the position of the compass.
map.compassRect = CGRect(x: map.frame.width/2 - 18, y: isIPhoneX ? 105.0 : 70.0 , width: 36, height: 36)
//If user long presses the map, it will add a Pin (waypoint) at that point
map.addGestureRecognizer(
UILongPressGestureRecognizer(target: self, action: #selector(ViewController.addPinAtTappedLocation(_:)))
)
//Each time user pans, if the map is following the user, it stops doing that.
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(ViewController.stopFollowingUser(_:)))
panGesture.delegate = self
map.addGestureRecognizer(panGesture)
locationManager.delegate = self
locationManager.startUpdatingLocation()
locationManager.startUpdatingHeading()
//let pinchGesture = UIPinchGestureRecognizer(target: self, action: "pinchGesture")
//map.addGestureRecognizer(pinchGesture)
//Preferences
map.tileServer = Preferences.shared.tileServer
map.useCache = Preferences.shared.useCache
useImperial = Preferences.shared.useImperial
//locationManager.activityType = Preferences.shared.locationActivityType
//
// Config user interface
//
// Set default zoom
let center = locationManager.location?.coordinate ?? CLLocationCoordinate2D(latitude: 8.90, longitude: -79.50)
let span = MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005)
let region = MKCoordinateRegion(center: center, span: span)
map.setRegion(region, animated: true)
self.view.addSubview(map)
addNotificationObservers()
//
// ---------------------- Build Interface Area -----------------------------
//
// HEADER
let font36 = UIFont(name: "DinCondensed-Bold", size: 36.0)
let font18 = UIFont(name: "DinAlternate-Bold", size: 18.0)
let font12 = UIFont(name: "DinAlternate-Bold", size: 12.0)
//add the app title Label (Branding, branding, branding! )
appTitleLabel.text = " Open GPX Tracker"
appTitleLabel.textAlignment = .left
appTitleLabel.font = UIFont.boldSystemFont(ofSize: 10)
//appTitleLabel.textColor = UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0)
appTitleLabel.textColor = UIColor.yellow
appTitleLabel.backgroundColor = UIColor(red: 58.0/255.0, green: 57.0/255.0, blue: 54.0/255.0, alpha: 0.80)
self.view.addSubview(appTitleLabel)
// CoordLabel
coordsLabel.textAlignment = .right
coordsLabel.font = font12
coordsLabel.textColor = UIColor.white
coordsLabel.text = kNotGettingLocationText
self.view.addSubview(coordsLabel)
// Tracked info
let iPhoneXdiff: CGFloat = isIPhoneX ? 40 : 0
//timeLabel
timeLabel.textAlignment = .right
timeLabel.font = font36
timeLabel.text = "00:00"
//timeLabel.shadowColor = UIColor.whiteColor()
//timeLabel.shadowOffset = CGSize(width: 1, height: 1)
//timeLabel.backgroundColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.5)
map.addSubview(timeLabel)
//speed Label
speedLabel.textAlignment = .right
speedLabel.font = font18
speedLabel.text = 0.00.toSpeed(useImperial: useImperial)
//timeLabel.backgroundColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.5)
map.addSubview(speedLabel)
//tracked distance
totalTrackedDistanceLabel.textAlignment = .right
totalTrackedDistanceLabel.font = font36
totalTrackedDistanceLabel.useImperial = useImperial
totalTrackedDistanceLabel.distance = 0.00
totalTrackedDistanceLabel.autoresizingMask = [.flexibleWidth, .flexibleLeftMargin, .flexibleRightMargin]
//timeLabel.backgroundColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.5)
map.addSubview(totalTrackedDistanceLabel)
currentSegmentDistanceLabel.textAlignment = .right
currentSegmentDistanceLabel.font = font18
currentSegmentDistanceLabel.useImperial = useImperial
currentSegmentDistanceLabel.distance = 0.00
currentSegmentDistanceLabel.autoresizingMask = [.flexibleWidth, .flexibleLeftMargin, .flexibleRightMargin]
//timeLabel.backgroundColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.5)
map.addSubview(currentSegmentDistanceLabel)
//about button
aboutButton.frame = CGRect(x: 5 + 8, y: 14 + 5 + 48 + 5 + iPhoneXdiff, width: 32, height: 32)
aboutButton.setImage(UIImage(named: "info"), for: UIControl.State())
aboutButton.setImage(UIImage(named: "info_high"), for: .highlighted)
aboutButton.addTarget(self, action: #selector(ViewController.openAboutViewController), for: .touchUpInside)
aboutButton.autoresizingMask = [.flexibleRightMargin]
//aboutButton.backgroundColor = kWhiteBackgroundColor
//aboutButton.layer.cornerRadius = 24
map.addSubview(aboutButton)
// Preferences button
preferencesButton.frame = CGRect(x: 5 + 10 + 48, y: 14 + 5 + 8 + iPhoneXdiff, width: 32, height: 32)
preferencesButton.setImage(UIImage(named: "prefs"), for: UIControl.State())
preferencesButton.setImage(UIImage(named: "prefs_high"), for: .highlighted)
preferencesButton.addTarget(self, action: #selector(ViewController.openPreferencesTableViewController), for: .touchUpInside)
preferencesButton.autoresizingMask = [.flexibleRightMargin]
//aboutButton.backgroundColor = kWhiteBackgroundColor
//aboutButton.layer.cornerRadius = 24
map.addSubview(preferencesButton)
// Share button
shareButton.frame = CGRect(x: 5 + 10 + 48 * 2, y: 14 + 5 + 8 + iPhoneXdiff, width: 32, height: 32)
shareButton.setImage(UIImage(named: "share"), for: UIControl.State())
shareButton.setImage(UIImage(named: "share_high"), for: .highlighted)
shareButton.addTarget(self, action: #selector(ViewController.openShare), for: .touchUpInside)
shareButton.autoresizingMask = [.flexibleRightMargin]
//aboutButton.backgroundColor = kWhiteBackgroundColor
//aboutButton.layer.cornerRadius = 24
map.addSubview(shareButton)
// Folder button
let folderW: CGFloat = kButtonSmallSize
let folderH: CGFloat = kButtonSmallSize
let folderX: CGFloat = folderW/2 + 5
let folderY: CGFloat = folderH/2 + 5 + 14 + iPhoneXdiff
folderButton.frame = CGRect(x: 0, y: 0, width: folderW, height: folderH)
folderButton.center = CGPoint(x: folderX, y: folderY)
folderButton.setImage(UIImage(named: "folder"), for: UIControl.State())
folderButton.setImage(UIImage(named: "folderHigh"), for: .highlighted)
folderButton.addTarget(self, action: #selector(ViewController.openFolderViewController), for: .touchUpInside)
folderButton.backgroundColor = kWhiteBackgroundColor
folderButton.layer.cornerRadius = 24
folderButton.autoresizingMask = [.flexibleRightMargin]
map.addSubview(folderButton)
// Add signal accuracy images and labels
signalImageView.image = signalImage0
signalImageView.frame = CGRect(x: self.view.frame.width/2 - 25.0, y: 14 + 5 + iPhoneXdiff, width: 50, height: 30)
signalImageView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin]
map.addSubview(signalImageView)
signalAccuracyLabel.frame = CGRect(x: self.view.frame.width/2 - 25.0, y: 14 + 5 + 30 + iPhoneXdiff , width: 50, height: 12)
signalAccuracyLabel.font = font12
signalAccuracyLabel.text = kUnknownAccuracyText
signalAccuracyLabel.textAlignment = .center
signalAccuracyLabel.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin]
map.addSubview(signalAccuracyLabel)
//
// Button Bar
//
// [ Small ] [ Small ] [ Large ] [Small] [ Small]
// [ (tracker) ]
//
// [ track ]
// [ follow] [ +Pin ] [ Pause ] [ Save ] [ Reset]
// [ Resume ]
//
// trackerX
// |
// |
// [-----------------------|--------------------------]
// map.frame/2 (center)
// Start/Pause button
trackerButton.layer.cornerRadius = kButtonLargeSize/2
trackerButton.setTitle(NSLocalizedString("START_TRACKING", comment: "no comment"), for: UIControl.State())
trackerButton.backgroundColor = kGreenButtonBackgroundColor
trackerButton.addTarget(self, action: #selector(ViewController.trackerButtonTapped), for: .touchUpInside)
trackerButton.isHidden = false
trackerButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
trackerButton.titleLabel?.numberOfLines = 2
trackerButton.titleLabel?.textAlignment = .center
map.addSubview(trackerButton)
// Pin Button (on the left of start)
newPinButton.layer.cornerRadius = kButtonSmallSize/2
newPinButton.backgroundColor = kWhiteBackgroundColor
newPinButton.setImage(UIImage(named: "addPin"), for: UIControl.State())
newPinButton.setImage(UIImage(named: "addPinHigh"), for: .highlighted)
newPinButton.addTarget(self, action: #selector(ViewController.addPinAtMyLocation), for: .touchUpInside)
//let newPinLongPress = UILongPressGestureRecognizer(target: self, action: Selector("newPinLongPress:"))
//newPinButton.addGestureRecognizer(newPinLongPress)
map.addSubview(newPinButton)
// Follow user button
followUserButton.layer.cornerRadius = kButtonSmallSize/2
followUserButton.backgroundColor = kWhiteBackgroundColor
//follow_user_high represents the user is being followed. Default status when app starts
followUserButton.setImage(UIImage(named: "follow_user_high"), for: UIControl.State())
followUserButton.setImage(UIImage(named: "follow_user_high"), for: .highlighted)
followUserButton.addTarget(self, action: #selector(ViewController.followButtonTroggler), for: .touchUpInside)
map.addSubview(followUserButton)
// Save button
saveButton.layer.cornerRadius = kButtonSmallSize/2
saveButton.setTitle(NSLocalizedString("SAVE", comment: "no comment"), for: UIControl.State())
saveButton.backgroundColor = kDisabledBlueButtonBackgroundColor
saveButton.addTarget(self, action: #selector(ViewController.saveButtonTapped), for: .touchUpInside)
saveButton.isHidden = false
saveButton.titleLabel?.textAlignment = .center
saveButton.titleLabel?.adjustsFontSizeToFitWidth = true
map.addSubview(saveButton)
// Reset button
resetButton.layer.cornerRadius = kButtonSmallSize/2
resetButton.setTitle(NSLocalizedString("RESET", comment: "no comment"), for: UIControl.State())
resetButton.backgroundColor = kDisabledRedButtonBackgroundColor
resetButton.addTarget(self, action: #selector(ViewController.resetButtonTapped), for: .touchUpInside)
resetButton.isHidden = false
resetButton.titleLabel?.textAlignment = .center
resetButton.titleLabel?.adjustsFontSizeToFitWidth = true
map.addSubview(resetButton)
addConstraints(isIPhoneX)
map.rotationGesture.delegate = self
updateAppearance()
if #available(iOS 13, *) {
shareActivityColor = .mainUIColor
}
}
/// Adds Constraints to subviews
///
/// The constraints will ensure that subviews will be positioned correctly, when there are orientation changes, or iPad split view width changes.
///
/// - Parameters:
/// - isIPhoneX: if device is >= iPhone X, bottom gap will be zero
func addConstraints(_ isIPhoneX: Bool) {
// MARK: App Title Bar
// Switch off all autoresizing masks translate
appTitleLabel.translatesAutoresizingMaskIntoConstraints = false
coordsLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: coordsLabel, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: -5).isActive = true
// not using self.topLayoutGuide as it will leave a gap between status bar and this, if used on non-notch devices
NSLayoutConstraint(item: appTitleLabel, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: isIPhoneX ? 40.0 : 20.0).isActive = true
NSLayoutConstraint(item: appTitleLabel, attribute: .lastBaseline, relatedBy: .equal, toItem: coordsLabel, attribute: .lastBaseline, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: appTitleLabel, attribute: .trailing, relatedBy: .equal, toItem: coordsLabel, attribute: .trailing, multiplier: 1, constant: 5).isActive = true
NSLayoutConstraint(item: appTitleLabel, attribute: .leading, relatedBy: .equal, toItem: coordsLabel, attribute: .leading, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: appTitleLabel, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 0).isActive = true
// MARK: Information Labels
/// offset from center, without obstructing signal view
let kSignalViewOffset: CGFloat = 25
// Switch off all autoresizing masks translate
timeLabel.translatesAutoresizingMaskIntoConstraints = false
speedLabel.translatesAutoresizingMaskIntoConstraints = false
totalTrackedDistanceLabel.translatesAutoresizingMaskIntoConstraints = false
currentSegmentDistanceLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: timeLabel, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: -7).isActive = true
NSLayoutConstraint(item: timeLabel, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: kSignalViewOffset).isActive = true
// self.topLayoutGuide takes care of the iPhone X safe area, iPhoneXdiff not needed
NSLayoutConstraint(item: timeLabel, attribute: .top, relatedBy: .equal, toItem: self.topLayoutGuide, attribute: .bottom, multiplier: 1, constant: 20).isActive = true
NSLayoutConstraint(item: speedLabel, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: -7).isActive = true
NSLayoutConstraint(item: speedLabel, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: kSignalViewOffset).isActive = true
NSLayoutConstraint(item: speedLabel, attribute: .top, relatedBy: .equal, toItem: timeLabel, attribute: .bottom, multiplier: 1, constant: -5).isActive = true
NSLayoutConstraint(item: totalTrackedDistanceLabel, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: -7).isActive = true
NSLayoutConstraint(item: totalTrackedDistanceLabel, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: kSignalViewOffset).isActive = true
NSLayoutConstraint(item: totalTrackedDistanceLabel, attribute: .top, relatedBy: .equal, toItem: speedLabel, attribute: .bottom, multiplier: 1, constant: 5).isActive = true
NSLayoutConstraint(item: currentSegmentDistanceLabel, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: -7).isActive = true
NSLayoutConstraint(item: currentSegmentDistanceLabel, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: kSignalViewOffset).isActive = true
NSLayoutConstraint(item: currentSegmentDistanceLabel, attribute: .top, relatedBy: .equal, toItem: totalTrackedDistanceLabel, attribute: .bottom, multiplier: 1, constant: 0).isActive = true
// MARK: Button Bar
// constants
let kBottomGap: CGFloat = isIPhoneX ? 0 : 15
let kBottomDistance: CGFloat = kBottomGap + 24
// Switch off all autoresizing masks translate
trackerButton.translatesAutoresizingMaskIntoConstraints = false
newPinButton.translatesAutoresizingMaskIntoConstraints = false
followUserButton.translatesAutoresizingMaskIntoConstraints = false
saveButton.translatesAutoresizingMaskIntoConstraints = false
resetButton.translatesAutoresizingMaskIntoConstraints = false
// set trackerButton to horizontal center of view
NSLayoutConstraint(item: trackerButton, attribute: .centerX, relatedBy: .equal, toItem: map, attribute: .centerX, multiplier: 1, constant: 0).isActive = true
// seperation distance between each button
NSLayoutConstraint(item: trackerButton, attribute: .leading, relatedBy: .equal, toItem: newPinButton, attribute: .trailing, multiplier: 1, constant: kButtonSeparation).isActive = true
NSLayoutConstraint(item: newPinButton, attribute: .leading, relatedBy: .equal, toItem: followUserButton, attribute: .trailing, multiplier: 1, constant: kButtonSeparation).isActive = true
NSLayoutConstraint(item: saveButton, attribute: .leading, relatedBy: .equal, toItem: trackerButton, attribute: .trailing, multiplier: 1, constant: kButtonSeparation).isActive = true
NSLayoutConstraint(item: resetButton, attribute: .leading, relatedBy: .equal, toItem: saveButton, attribute: .trailing, multiplier: 1, constant: kButtonSeparation).isActive = true
// seperation distance between button and bottom of view
NSLayoutConstraint(item: self.bottomLayoutGuide, attribute: .top, relatedBy: .equal, toItem: followUserButton, attribute: .bottom, multiplier: 1, constant: kBottomDistance).isActive = true
NSLayoutConstraint(item: self.bottomLayoutGuide, attribute: .top, relatedBy: .equal, toItem: newPinButton, attribute: .bottom, multiplier: 1, constant: kBottomDistance).isActive = true
NSLayoutConstraint(item: self.bottomLayoutGuide, attribute: .top, relatedBy: .equal, toItem: trackerButton, attribute: .bottom, multiplier: 1, constant: kBottomGap).isActive = true
NSLayoutConstraint(item: self.bottomLayoutGuide, attribute: .top, relatedBy: .equal, toItem: saveButton, attribute: .bottom, multiplier: 1, constant: kBottomDistance).isActive = true
NSLayoutConstraint(item: self.bottomLayoutGuide, attribute: .top, relatedBy: .equal, toItem: resetButton, attribute: .bottom, multiplier: 1, constant: kBottomDistance).isActive = true
// fixed dimensions for all buttons
NSLayoutConstraint(item: followUserButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: kButtonSmallSize).isActive = true
NSLayoutConstraint(item: followUserButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: kButtonSmallSize).isActive = true
NSLayoutConstraint(item: newPinButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: kButtonSmallSize).isActive = true
NSLayoutConstraint(item: newPinButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: kButtonSmallSize).isActive = true
NSLayoutConstraint(item: trackerButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: kButtonLargeSize).isActive = true
NSLayoutConstraint(item: trackerButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: kButtonLargeSize).isActive = true
NSLayoutConstraint(item: saveButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: kButtonSmallSize).isActive = true
NSLayoutConstraint(item: saveButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: kButtonSmallSize).isActive = true
NSLayoutConstraint(item: resetButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: kButtonSmallSize).isActive = true
NSLayoutConstraint(item: resetButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: kButtonSmallSize).isActive = true
}
/// For handling compass location changes when orientation is switched.
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
DispatchQueue.main.async(){
// set the new position of the compass.
self.map.compassRect = CGRect(x: size.width/2 - 18, y: 70.0 , width: 36, height: 36)
// update compass frame location
self.map.layoutSubviews()
}
}
/// Will update polyline color when invoked
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
updatePolylineColor()
}
/// Updates polyline color
func updatePolylineColor() {
for overlay in map.overlays {
if overlay is MKPolyline {
map.removeOverlay(overlay)
map.addOverlay(overlay)
}
}
}
///
/// Asks the system to notify the app on some events
///
/// Current implementation requests the system to notify the app:
///
/// 1. whenever it enters background
/// 2. whenever it becomes active
/// 3. whenever it will terminate
/// 4. whenever it receives a file from Apple Watch
/// 5. whenever it should load file from Core Data recovery mechanism
///
func addNotificationObservers() {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(ViewController.didEnterBackground),
name: UIApplication.didEnterBackgroundNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(applicationWillTerminate), name: UIApplication.willTerminateNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(presentReceivedFile(_:)), name: .didReceiveFileFromAppleWatch, object: nil)
notificationCenter.addObserver(self, selector: #selector(loadRecoveredFile(_:)), name: .loadRecoveredFile, object: nil)
notificationCenter.addObserver(self, selector: #selector(updateAppearance), name: .updateAppearance, object: nil)
}
///
/// Removes the notification observers
///
func removeNotificationObservers() {
NotificationCenter.default.removeObserver(self)
}
/// To update appearance when mapView requests to do so
@objc func updateAppearance() {
if #available(iOS 13, *) {
setNeedsStatusBarAppearanceUpdate()
updatePolylineColor()
}
}
///
/// Presents alert when file received from Apple Watch
///
@objc func presentReceivedFile(_ notification: Notification) {
DispatchQueue.main.async {
guard let fileName = notification.userInfo?["fileName"] as? String? else { return }
// alert to display to notify user that file has been received.
let alertTitle = NSLocalizedString("WATCH_FILE_RECEIVED_TITLE", comment: "no comment")
let alertMessage = NSLocalizedString("WATCH_FILE_RECEIVED_MESSAGE", comment: "no comment")
let controller = UIAlertController(title: alertTitle, message: String(format: alertMessage, fileName ?? ""), preferredStyle: .alert)
let action = UIAlertAction(title: NSLocalizedString("DONE", comment: "no comment"), style: .default) {
(action) in
print("ViewController:: Presented file received message from WatchConnectivity Session")
}
controller.addAction(action)
self.present(controller, animated: true, completion: nil)
}
}
/// returns a string with the format of current date dd-MMM-yyyy-HHmm' (20-Jun-2018-1133)
///
func defaultFilename() -> String {
let defaultDate = DefaultDateFormat()
//let dateFormatter = DateFormatter()
//dateFormatter.dateFormat = "dd-MMM-yyyy-HHmm"
let dateStr = defaultDate.getDateFromPrefs()
print("fileName:" + dateStr)//dateFormatter.string(from: Date()))
return dateStr//dateFormatter.string(from: Date())
}
@objc func loadRecoveredFile(_ notification: Notification) {
guard let root = notification.userInfo?["recoveredRoot"] as? GPXRoot else {
return
}
guard let fileName = notification.userInfo?["fileName"] as? String else {
return
}
lastGpxFilename = fileName
// adds last file name to core data as well
self.map.coreDataHelper.add(toCoreData: fileName, willContinueAfterSave: false)
//force reset timer just in case reset does not do it
self.stopWatch.reset()
//load data
self.map.continueFromGPXRoot(root)
//stop following user
self.followUser = false
//center map in GPX data
self.map.regionToGPXExtent()
self.gpxTrackingStatus = .paused
self.totalTrackedDistanceLabel.distance = self.map.session.totalTrackedDistance
}
///
/// Called when the application Becomes active (background -> foreground) this function verifies if
/// it has permissions to get the location.
///
@objc func applicationDidBecomeActive() {
print("viewController:: applicationDidBecomeActive wasSentToBackground: \(wasSentToBackground) locationServices: \(CLLocationManager.locationServicesEnabled())")
//If the app was never sent to background do nothing
if !wasSentToBackground {
return
}
checkLocationServicesStatus()
locationManager.startUpdatingLocation()
locationManager.startUpdatingHeading()
}
///
/// Actions to do in case the app entered in background
///
/// In current implementation if the app is not tracking it requests the OS to stop
/// sharing the location to save battery.
///
///
@objc func didEnterBackground() {
wasSentToBackground = true // flag the application was sent to background
print("viewController:: didEnterBackground")
if gpxTrackingStatus != .tracking {
locationManager.stopUpdatingLocation()
}
}
///
/// Actions to do when the app will terminate
///
/// In current implementation it removes all the temporary files that may have been created
@objc func applicationWillTerminate() {
print("viewController:: applicationWillTerminate")
GPXFileManager.removeTemporaryFiles()
if gpxTrackingStatus == .notStarted {
map.coreDataHelper.deleteAllTrackFromCoreData()
map.coreDataHelper.deleteAllWaypointsFromCoreData()
}
}
///
/// Displays the view controller with the list of GPX Files.
///
@objc func openFolderViewController() {
print("openFolderViewController")
let vc = GPXFilesTableViewController(nibName: nil, bundle: nil)
vc.delegate = self
let navController = UINavigationController(rootViewController: vc)
self.present(navController, animated: true) { () -> Void in }
}
///
/// Displays the view controller with the About information.
///
@objc func openAboutViewController() {
let vc = AboutViewController(nibName: nil, bundle: nil)
let navController = UINavigationController(rootViewController: vc)
self.present(navController, animated: true) { () -> Void in }
}
///
/// Opens Preferences table view controller
///
@objc func openPreferencesTableViewController() {
print("openPreferencesTableViewController")
let vc = PreferencesTableViewController(style: .grouped)
vc.delegate = self
let navController = UINavigationController(rootViewController: vc)
self.present(navController, animated: true) { () -> Void in }
}
/// Opens an Activity View Controller to share the file
@objc func openShare() {
print("ViewController: Share Button tapped")
// async such that process is done in background
DispatchQueue.global(qos: .utility).async {
// UI code
DispatchQueue.main.sync {
self.shouldShowShareActivityIndicator(true)
}
//Create a temporary file
let filename = self.lastGpxFilename.isEmpty ? self.defaultFilename() : self.lastGpxFilename
let gpxString: String = self.map.exportToGPXString()
let tmpFile = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("\(filename).gpx")
GPXFileManager.saveToURL(tmpFile, gpxContents: gpxString)
//Add it to the list of tmpFiles.
//Note: it may add more than once the same file to the list.
// UI code
DispatchQueue.main.sync {
//Call Share activity View controller
let activityViewController = UIActivityViewController(activityItems: [tmpFile], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.shareButton
activityViewController.popoverPresentationController?.sourceRect = self.shareButton.bounds
self.present(activityViewController, animated: true, completion: nil)
self.shouldShowShareActivityIndicator(false)
}
}
}
/// Displays spinning activity indicator for share button when true
func shouldShowShareActivityIndicator(_ isTrue: Bool) {
// setup
shareActivityIndicator.color = shareActivityColor
shareActivityIndicator.frame = CGRect(x: 0, y: 0, width: 32, height: 32)
shareActivityIndicator.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
if isTrue {
// cross dissolve from button to indicator
UIView.transition(with: self.shareButton, duration: 0.35, options: [.transitionCrossDissolve], animations: {
self.shareButton.addSubview(self.shareActivityIndicator)
}, completion: nil)
shareActivityIndicator.startAnimating()
shareButton.setImage(nil, for: UIControl.State())
shareButton.isUserInteractionEnabled = false
}
else {
// cross dissolve from indicator to button
UIView.transition(with: self.shareButton, duration: 0.35, options: [.transitionCrossDissolve], animations: {
self.shareActivityIndicator.removeFromSuperview()