-
Notifications
You must be signed in to change notification settings - Fork 299
/
NavigationViewController.swift
1026 lines (816 loc) · 44.2 KB
/
NavigationViewController.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
import UIKit
import MapboxCoreNavigation
import MapboxDirections
import MapboxSpeech
import AVFoundation
import UserNotifications
import MobileCoreServices
import MapboxMaps
import MapboxCoreMaps
import Turf
/**
A container view controller is a view controller that behaves as a navigation component; that is, it responds as the user progresses along a route according to the `NavigationServiceDelegate` protocol.
*/
public typealias ContainerViewController = UIViewController & NavigationComponent
/**
`NavigationViewController` is a fully-featured user interface for turn-by-turn navigation. Do not confuse it with the `NavigationController` class in UIKit.
You initialize a navigation view controller based on a predefined `Route` and `NavigationOptions`. As the user progresses along the route, the navigation view controller shows their surroundings and the route line on a map. Banners above and below the map display key information pertaining to the route. A list of steps and a feedback mechanism are accessible via the navigation view controller.
To be informed of significant events and decision points as the user progresses along the route, set the `NavigationService.delegate` property of the `NavigationService` that you provide when creating the navigation options.
`CarPlayNavigationViewController` manages the corresponding user interface on a CarPlay screen.
*/
open class NavigationViewController: UIViewController, NavigationStatusPresenter, NavigationViewData {
/**
A `Route` object constructed by [MapboxDirections](https://docs.mapbox.com/ios/api/directions/) along with its index in a `RouteResponse`.
In cases where you need to update the route after navigation has started, you can set a new route here and `NavigationViewController` will update its UI accordingly.
*/
public var indexedRoute: IndexedRoute {
get {
return navigationService.indexedRoute
}
set {
navigationService.indexedRoute = newValue
for component in navigationComponents {
component.navigationService(navigationService, didRerouteAlong: newValue.0, at: nil, proactive: false)
}
}
}
/**
A `Route` object constructed by [MapboxDirections](https://docs.mapbox.com/ios/api/directions/).
*/
public var route: Route {
return indexedRoute.0
}
public var routeOptions: RouteOptions {
get {
return navigationService.routeProgress.routeOptions
}
}
/**
An instance of `Directions` need for rerouting. See [Mapbox Directions](https://docs.mapbox.com/ios/api/directions/) for further information.
*/
public var directions: Directions {
return navigationService!.directions
}
/**
The receiver’s delegate.
*/
public weak var delegate: NavigationViewControllerDelegate?
/**
The voice controller that vocalizes spoken instructions along the route at the appropriate times.
*/
public var voiceController: RouteVoiceController!
/**
The `NavigationMapView` displayed inside the view controller.
- note: Do not change `NavigationMapView.delegate` property; instead, implement the corresponding methods on `NavigationViewControllerDelegate`.
*/
@objc public var navigationMapView: NavigationMapView? {
get {
return navigationView.navigationMapView
}
}
/**
Determines whether the user location annotation is moved from the raw user location reported by the device to the nearest location along the route.
By default, this property is set to `true`, causing the user location annotation to be snapped to the route.
*/
public var snapsUserLocationAnnotationToRoute = true
/**
Toggles sending of UILocalNotification upon upcoming steps when application is in the background. Defaults to `true`.
*/
public var sendsNotifications: Bool = true
/**
Shows a button that allows drivers to report feedback such as accidents, closed roads, poor instructions, etc. Defaults to `true`.
*/
public var showsReportFeedback: Bool = true {
didSet {
ornamentsController?.reportButton.isHidden = !showsReportFeedback
showsEndOfRouteFeedback = showsReportFeedback
}
}
/**
Shows End of route Feedback UI when the route controller arrives at the final destination.
Defaults to `true.`
*/
public var showsEndOfRouteFeedback: Bool {
get {
arrivalController?.showsEndOfRoute ?? false
}
set {
arrivalController?.showsEndOfRoute = newValue
}
}
/**
Shows the current speed limit on the map view.
The default value of this property is `true`.
*/
public var showsSpeedLimits: Bool {
get {
ornamentsController?.showsSpeedLimits ?? false
}
set {
ornamentsController?.showsSpeedLimits = newValue
}
}
/**
If true, the map style and UI will automatically be updated given the time of day.
*/
public var automaticallyAdjustsStyleForTimeOfDay = true {
didSet {
styleManager.automaticallyAdjustsStyleForTimeOfDay = automaticallyAdjustsStyleForTimeOfDay
}
}
/**
If `true`, `UIApplication.isIdleTimerDisabled` is set to `true` in `viewWillAppear(_:)` and `false` in `viewWillDisappear(_:)`. If your application manages the idle timer itself, set this property to `false`.
*/
public var shouldManageApplicationIdleTimer = true
/**
Allows to control highlighting of the destination building on arrival. By default destination buildings will not be highlighted.
*/
public var waypointStyle: WaypointStyle = .annotation
/**
Controls whether the main route style layer and its casing disappears
as the user location puck travels over it. Defaults to `false`.
If `true`, the part of the route that has been traversed will be
rendered with full transparency, to give the illusion of a
disappearing route. To customize the color that appears on the
traversed section of a route, override the `traversedRouteColor` property
for the `NavigationMapView.appearance()`.
*/
public var routeLineTracksTraversal: Bool {
get {
navigationMapView?.routeLineTracksTraversal ?? false
}
set {
navigationMapView?.routeLineTracksTraversal = newValue
}
}
/**
Controls whether or not the FeedbackViewController shows a second level of detail for feedback items.
Defaults to `false`.
*/
public var detailedFeedbackEnabled: Bool {
get {
ornamentsController?.detailedFeedbackEnabled ?? false
}
set {
ornamentsController?.detailedFeedbackEnabled = newValue
}
}
var topViewController: ContainerViewController?
var bottomViewController: ContainerViewController?
/**
The position of floating buttons in a navigation view. The default value is `MapOrnamentPosition.topTrailing`.
*/
open var floatingButtonsPosition: MapOrnamentPosition? {
get {
ornamentsController?.floatingButtonsPosition
}
set {
ornamentsController?.floatingButtonsPosition = newValue
}
}
/**
The floating buttons in an array of UIButton in navigation view. The default floating buttons include the overview, mute and feedback report button. The default type of the floatingButtons is `FloatingButton`, which is declared with `FloatingButton.rounded(image:selectedImage:size:)` to be consistent.
*/
open var floatingButtons: [UIButton]? {
get {
ornamentsController?.floatingButtons
}
set {
ornamentsController?.floatingButtons = newValue
}
}
var navigationComponents: [NavigationComponent] {
var components: [NavigationComponent] = []
if let routeOverlayController = routeOverlayController {
components.append(routeOverlayController)
}
if let cameraController = cameraController {
components.append(cameraController)
}
if let overlayController = ornamentsController {
components.append(overlayController)
}
if let topViewController = topViewController {
components.append(topViewController)
}
if let bottomViewController = bottomViewController {
components.append(bottomViewController)
}
return components
}
/**
A Boolean value that determines whether the map annotates the locations at which instructions are spoken for debugging purposes.
Defaults to `false`.
*/
public var annotatesSpokenInstructions: Bool {
get {
routeOverlayController?.annotatesSpokenInstructions ?? false
}
set {
routeOverlayController?.annotatesSpokenInstructions = newValue
}
}
var styleManager: StyleManager!
var currentStatusBarStyle: UIStatusBarStyle = .default
open override var preferredStatusBarStyle: UIStatusBarStyle {
get {
return currentStatusBarStyle
}
}
/**
The navigation service that coordinates the view controller’s nonvisual components, tracking the user’s location as they proceed along the route.
*/
private(set) public var navigationService: NavigationService! {
didSet {
arrivalController?.destination = route.legs.last?.destination
}
}
private var traversingTunnel = false
private var approachingDestinationThreshold: CLLocationDistance = 250.0
private var passedApproachingDestinationThreshold: Bool = false
private var currentLeg: RouteLeg?
private var foundAllBuildings = false
var arrivalController: ArrivalController?
var cameraController: CameraController?
var ornamentsController: NavigationMapView.OrnamentsController?
var routeOverlayController: NavigationMapView.RouteOverlayController?
var viewObservers: [NavigationComponentDelegate] = []
var mapTileStore: TileStoreConfiguration.Location? = .default
// MARK: - NavigationViewData implementation
var navigationView: NavigationView! {
return (view as! NavigationView)
}
var router: Router! {
navigationService.router
}
var containerViewController: UIViewController! {
return self
}
// MARK: - Initialization methods
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
Initializes a navigation view controller that presents the user interface for following a predefined route based on the given options.
The route may come directly from the completion handler of the [MapboxDirections](https://docs.mapbox.com/ios/api/directions/) framework’s `Directions.calculate(_:completionHandler:)` method, or it may be unarchived or created from a JSON object.
- parameter route: The route to navigate along.
- parameter routeIndex: The index of the route within the original `RouteResponse` object.
- parameter routeOptions: The route options used to get the route.
- parameter navigationOptions: The navigation options to use for the navigation session.
*/
required public init(for route: Route, routeIndex: Int, routeOptions: RouteOptions, navigationOptions: NavigationOptions? = nil) {
if let options = navigationOptions {
mapTileStore = options.tileStoreConfiguration.mapLocation
}
super.init(nibName: nil, bundle: nil)
if !(routeOptions is NavigationRouteOptions) {
print("`Route` was created using `RouteOptions` and not `NavigationRouteOptions`. Although not required, this may lead to a suboptimal navigation experience. Without `NavigationRouteOptions`, it is not guaranteed you will get congestion along the route line, better ETAs and ETA label color dependent on congestion.")
}
navigationService = navigationOptions?.navigationService ?? MapboxNavigationService(route: route,
routeIndex: routeIndex,
routeOptions: routeOptions,
tileStoreLocation: navigationOptions?.tileStoreConfiguration.navigatorLocation ?? .default)
navigationService.delegate = self
let credentials = navigationService.directions.credentials
voiceController = navigationOptions?.voiceController ?? RouteVoiceController(navigationService: navigationService,
accessToken: credentials.accessToken,
host: credentials.host.absoluteString)
NavigationSettings.shared.distanceUnit = routeOptions.locale.usesMetric ? .kilometer : .mile
setupControllers(navigationOptions)
setupStyleManager(navigationOptions)
subviewInits.append { [weak self] in
if let predictiveCacheOptions = navigationOptions?.predictiveCacheOptions {
self?.navigationMapView?.enablePredictiveCaching(options: predictiveCacheOptions,
tileStoreConfiguration: navigationOptions?.tileStoreConfiguration)
}
}
}
/**
Initializes a navigation view controller with the given route and navigation service.
- parameter route: The route to navigate along.
- parameter routeIndex: The index of the route within the original `RouteResponse` object.
- parameter routeOptions: the options object used to generate the route.
- parameter navigationService: The navigation service that manages navigation along the route.
*/
convenience init(route: Route, routeIndex: Int, routeOptions: RouteOptions, navigationService service: NavigationService) {
let options = NavigationOptions(navigationService: service)
self.init(for: route, routeIndex: routeIndex, routeOptions: routeOptions, navigationOptions: options)
}
deinit {
navigationService.stop()
}
fileprivate func handleCancelAction() {
if delegate?.navigationViewControllerDidDismiss(self, byCanceling: true) != nil {
// The receiver should handle dismissal of the NavigationViewController
} else {
dismiss(animated: true, completion: nil)
}
}
// MARK: - Setting-up methods
func setupStyleManager(_ navigationOptions: NavigationOptions?) {
styleManager = StyleManager()
styleManager.delegate = self
styleManager.styles = navigationOptions?.styles ?? [DayStyle(), NightStyle()]
if let currentStyle = styleManager.currentStyle {
updateMapStyle(currentStyle)
}
}
func setupControllers(_ navigationOptions: NavigationOptions?) {
arrivalController = ArrivalController(self)
routeOverlayController = NavigationMapView.RouteOverlayController(self)
cameraController = CameraController(self)
ornamentsController = NavigationMapView.OrnamentsController(self, eventsManager: navigationService.eventsManager)
viewObservers = [routeOverlayController!, cameraController!, ornamentsController!, arrivalController!]
subviewInits.append { [weak self] in
if let topBanner = self?.addTopBanner(navigationOptions),
let bottomBanner = self?.addBottomBanner(navigationOptions) {
self?.ornamentsController?.embedBanners(topBanner: topBanner,
bottomBanner: bottomBanner)
}
}
arrivalController?.destination = route.legs.last?.destination
ornamentsController?.reportButton.isHidden = !showsReportFeedback
if let centerCoordinate = navigationService.routeProgress.route.shape?.coordinates.first {
navigationMapView?.setInitialCamera(centerCoordinate)
}
}
func addTopBanner(_ navigationOptions: NavigationOptions?) -> ContainerViewController {
let topBanner = navigationOptions?.topBanner ?? {
let viewController: TopBannerViewController = .init()
viewController.delegate = self
viewController.statusView.addTarget(self, action: #selector(NavigationViewController.didChangeSpeed(_:)), for: .valueChanged)
return viewController
}()
topViewController = topBanner
return topBanner
}
func addBottomBanner(_ navigationOptions: NavigationOptions?) -> ContainerViewController {
let bottomBanner = navigationOptions?.bottomBanner ?? {
let viewController: BottomBannerViewController = .init()
viewController.delegate = self
return viewController
}()
bottomViewController = bottomBanner
return bottomBanner
}
// MARK: - UIViewController lifecycle methods
open override func loadView() {
let frame = parent?.view.bounds ?? UIScreen.main.bounds
view = NavigationView(delegate: self, frame: frame, tileStoreLocation: mapTileStore)
}
/**
Array of initialization hooks to be called at `NavigationViewController.viewDidLoad`.
Once main view is loaded, `NavigationService` starts, and each UI component should be ready to accept navigation events and updates. At the same time, various components require embedding, which triggers main view initialization, which triggers service start... To break this cycle, wrap any custom subview configuration here, to avoid triggering main view initialization before it is required.
*/
private var subviewInits: [() -> ()] = []
override open func viewDidLoad() {
super.viewDidLoad()
subviewInits.forEach {
$0()
}
subviewInits.removeAll()
viewObservers.forEach {
$0.navigationViewDidLoad(view)
}
// Initialize voice controller if it hasn't been overridden.
// This is optional and lazy so it can be mutated by the developer after init.
_ = voiceController
// Start the navigation service on presentation.
self.navigationService.start()
view.clipsToBounds = true
guard let firstInstruction = navigationService.routeProgress.currentLegProgress.currentStepProgress.currentVisualInstruction else {
return
}
navigationService(navigationService, didPassVisualInstructionPoint: firstInstruction, routeProgress: navigationService.routeProgress)
// By default `NavigationCamera` in active guidance navigation should be set to `NavigationCameraState.following` state.
navigationMapView?.navigationCamera.follow()
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewObservers.forEach {
$0.navigationViewWillAppear(animated)
}
if shouldManageApplicationIdleTimer {
UIApplication.shared.isIdleTimerDisabled = true
}
notifyUserAboutLowVolumeIfNeeded()
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
viewObservers.forEach {
$0.navigationViewDidAppear(animated)
}
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
viewObservers.forEach {
$0.navigationViewWillDisappear(animated)
}
if shouldManageApplicationIdleTimer {
UIApplication.shared.isIdleTimerDisabled = false
}
}
open override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
viewObservers.forEach {
$0.navigationViewDidDisappear(animated)
}
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
viewObservers.forEach {
$0.navigationViewDidLayoutSubviews()
}
}
open override func preferredContentSizeDidChange(forChildContentContainer container: UIContentContainer) {
arrivalController?.updatePreferredContentSize(container.preferredContentSize)
}
func notifyUserAboutLowVolumeIfNeeded() {
guard !(navigationService.locationManager is SimulatedLocationManager) else { return }
guard !NavigationSettings.shared.voiceMuted else { return }
guard AVAudioSession.sharedInstance().outputVolume <= NavigationViewMinimumVolumeForWarning else { return }
let title = NSLocalizedString("INAUDIBLE_INSTRUCTIONS_CTA", bundle: .mapboxNavigation, value: "Adjust Volume to Hear Instructions", comment: "Label indicating the device volume is too low to hear spoken instructions and needs to be manually increased")
showStatus(title: title, spinner: false, duration: 3, animated: true, interactive: false)
}
// MARK: - Containerization methods
func embed(_ child: UIViewController, in container: UIView, constrainedBy constraints: ((NavigationViewController, UIViewController) -> [NSLayoutConstraint])?) {
child.willMove(toParent: self)
addChild(child)
container.addSubview(child.view)
if let childConstraints: [NSLayoutConstraint] = constraints?(self, child) {
view.addConstraints(childConstraints)
}
child.didMove(toParent: self)
}
// MARK: - Route controller notification handling methods
func scheduleLocalNotification(_ routeProgress: RouteProgress) {
// Remove any notification about an already completed maneuver, even if there isn’t another notification to replace it with yet.
let identifier = "com.mapbox.route_progress_instruction"
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [identifier])
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [identifier])
guard sendsNotifications else { return }
guard UIApplication.shared.applicationState == .background else { return }
let currentLegProgress = routeProgress.currentLegProgress
if currentLegProgress.currentStepProgress.currentSpokenInstruction !=
currentLegProgress.currentStep.instructionsSpokenAlongStep?.last {
return
}
guard let instruction = currentLegProgress.currentStep.instructionsDisplayedAlongStep?.last else { return }
let content = UNMutableNotificationContent()
if let primaryText = instruction.primaryInstruction.text {
content.title = primaryText
}
if let secondaryText = instruction.secondaryInstruction?.text {
content.subtitle = secondaryText
}
let imageColor: UIColor
if #available(iOS 12.0, *) {
switch traitCollection.userInterfaceStyle {
case .dark:
imageColor = .white
case .light, .unspecified:
imageColor = .black
@unknown default:
imageColor = .black
}
} else {
imageColor = .black
}
if let image = instruction.primaryInstruction.maneuverImage(side: instruction.drivingSide, color: imageColor, size: CGSize(width: 72, height: 72)) {
// Bake in any transform required for left turn arrows etc.
let imageData = UIGraphicsImageRenderer(size: image.size).pngData { (context) in
image.draw(at: .zero)
}
let temporaryURL = FileManager.default.temporaryDirectory.appendingPathComponent("com.mapbox.navigation.notification-icon.png")
do {
try imageData.write(to: temporaryURL)
let iconAttachment = try UNNotificationAttachment(identifier: "maneuver", url: temporaryURL, options: [UNNotificationAttachmentOptionsTypeHintKey: kUTTypePNG])
content.attachments = [iconAttachment]
} catch {
NSLog("Failed to create UNNotificationAttachment with error: \(error.localizedDescription).")
}
}
let notificationRequest = UNNotificationRequest(identifier: identifier, content: content, trigger: nil)
UNUserNotificationCenter.current().add(notificationRequest, withCompletionHandler: nil)
}
public func showStatus(title: String, spinner: Bool, duration: TimeInterval, animated: Bool, interactive: Bool) {
navigationComponents.compactMap({ $0 as? NavigationStatusPresenter }).forEach {
$0.showStatus(title: title, spinner: spinner, duration: duration, animated: animated, interactive: interactive)
}
}
}
extension NavigationViewController: NavigationViewDelegate {
func navigationView(_ view: NavigationView, didTapCancelButton: CancelButton) {
handleCancelAction()
}
}
// MARK: - NavigationServiceDelegate methods
extension NavigationViewController: NavigationServiceDelegate {
public func navigationService(_ service: NavigationService, shouldRerouteFrom location: CLLocation) -> Bool {
let defaultBehavior = RouteController.DefaultBehavior.shouldRerouteFromLocation
let componentsWantReroute = navigationComponents.allSatisfy { $0.navigationService(service, shouldRerouteFrom: location) }
return componentsWantReroute && (delegate?.navigationViewController(self, shouldRerouteFrom: location) ?? defaultBehavior)
}
public func navigationService(_ service: NavigationService, willRerouteFrom location: CLLocation) {
for component in navigationComponents {
component.navigationService(service, willRerouteFrom: location)
}
delegate?.navigationViewController(self, willRerouteFrom: location)
}
public func navigationService(_ service: NavigationService, didRerouteAlong route: Route, at location: CLLocation?, proactive: Bool) {
for component in navigationComponents {
component.navigationService(service, didRerouteAlong: route, at: location, proactive: proactive)
}
delegate?.navigationViewController(self, didRerouteAlong: route)
}
public func navigationService(_ service: NavigationService, didFailToRerouteWith error: Error) {
for component in navigationComponents {
component.navigationService(service, didFailToRerouteWith: error)
}
delegate?.navigationViewController(self, didFailToRerouteWith: error)
}
public func navigationService(_ service: NavigationService, didRefresh routeProgress: RouteProgress) {
for component in navigationComponents {
component.navigationService(service, didRefresh: routeProgress)
}
delegate?.navigationViewController(self, didRefresh: routeProgress)
}
public func navigationService(_ service: NavigationService, shouldDiscard location: CLLocation) -> Bool {
let defaultBehavior = RouteController.DefaultBehavior.shouldDiscardLocation
let componentsWantToDiscard = navigationComponents.allSatisfy { $0.navigationService(service, shouldDiscard: location) }
return componentsWantToDiscard && (delegate?.navigationViewController(self, shouldDiscard: location) ?? defaultBehavior)
}
public func navigationService(_ service: NavigationService, didUpdate progress: RouteProgress, with location: CLLocation, rawLocation: CLLocation) {
// Check to see if we're in a tunnel.
checkTunnelState(at: location, along: progress)
// Pass the message onto our navigation components.
for component in navigationComponents {
component.navigationService(service, didUpdate: progress, with: location, rawLocation: rawLocation)
}
// If the user has arrived, don't snap the user puck.
// In case if user drives beyond the waypoint, we should accurately depict this.
guard let destination = progress.currentLeg.destination else {
preconditionFailure("Current leg has no destination")
}
let shouldPrevent = navigationService.delegate?.navigationService(navigationService, shouldPreventReroutesWhenArrivingAt: destination) ?? RouteController.DefaultBehavior.shouldPreventReroutesWhenArrivingAtWaypoint
let userHasArrivedAndShouldPreventRerouting = shouldPrevent && !progress.currentLegProgress.userHasArrivedAtWaypoint
if snapsUserLocationAnnotationToRoute, userHasArrivedAndShouldPreventRerouting {
ornamentsController?.labelCurrentRoad(at: rawLocation, suggestedName: roadName(at: rawLocation), for: location)
navigationMapView?.updateUserCourseView(location, animated: true)
} else {
ornamentsController?.labelCurrentRoad(at: rawLocation, suggestedName: roadName(at: rawLocation))
}
attemptToHighlightBuildings(progress, with: location)
// Finally, pass the message onto the `NavigationViewControllerDelegate`.
delegate?.navigationViewController(self, didUpdate: progress, with: location, rawLocation: rawLocation)
}
public func navigationService(_ service: NavigationService, didPassSpokenInstructionPoint instruction: SpokenInstruction, routeProgress: RouteProgress) {
for component in navigationComponents {
component.navigationService(service, didPassSpokenInstructionPoint: instruction, routeProgress: routeProgress)
}
scheduleLocalNotification(routeProgress)
}
public func navigationService(_ service: NavigationService, didPassVisualInstructionPoint instruction: VisualInstructionBanner, routeProgress: RouteProgress) {
for component in navigationComponents {
component.navigationService(service, didPassVisualInstructionPoint: instruction, routeProgress: routeProgress)
}
}
public func navigationService(_ service: NavigationService, willArriveAt waypoint: Waypoint, after remainingTimeInterval: TimeInterval, distance: CLLocationDistance) {
for component in navigationComponents {
component.navigationService(service, willArriveAt: waypoint, after: remainingTimeInterval, distance: distance)
}
delegate?.navigationViewController(self, willArriveAt: waypoint, after: remainingTimeInterval, distance: distance)
}
public func navigationService(_ service: NavigationService, didArriveAt waypoint: Waypoint) -> Bool {
let defaultBehavior = RouteController.DefaultBehavior.didArriveAtWaypoint
let componentsWantAdvance = navigationComponents.allSatisfy { $0.navigationService(service, didArriveAt: waypoint) }
let advancesToNextLeg = componentsWantAdvance && (delegate?.navigationViewController(self, didArriveAt: waypoint) ?? defaultBehavior)
arrivalController?.showEndOfRouteIfNeeded(self,
advancesToNextLeg: advancesToNextLeg,
completion: nil,
onDismiss: { [weak self] in
self?.navigationService.endNavigation(feedback: $0)
self?.handleCancelAction()
})
return advancesToNextLeg
}
public func navigationService(_ service: NavigationService, willBeginSimulating progress: RouteProgress, becauseOf reason: SimulationIntent) {
for component in navigationComponents {
component.navigationService(service, willBeginSimulating: progress, becauseOf: reason)
}
}
public func navigationService(_ service: NavigationService, didBeginSimulating progress: RouteProgress, becauseOf reason: SimulationIntent) {
for component in navigationComponents {
component.navigationService(service, didBeginSimulating: progress, becauseOf: reason)
}
}
public func navigationService(_ service: NavigationService, willEndSimulating progress: RouteProgress, becauseOf reason: SimulationIntent) {
for component in navigationComponents {
component.navigationService(service, willEndSimulating: progress, becauseOf: reason)
}
}
public func navigationService(_ service: NavigationService, didEndSimulating progress: RouteProgress, becauseOf reason: SimulationIntent) {
for component in navigationComponents {
component.navigationService(service, didEndSimulating: progress, becauseOf: reason)
}
}
private func checkTunnelState(at location: CLLocation, along progress: RouteProgress) {
let inTunnel = navigationService.isInTunnel(at: location, along: progress)
// Entering tunnel
if !traversingTunnel, inTunnel {
traversingTunnel = true
styleManager.applyStyle(type: .night)
}
// Exiting tunnel
if traversingTunnel, !inTunnel {
traversingTunnel = false
styleManager.timeOfDayChanged()
}
}
public func navigationService(_ service: NavigationService, shouldPreventReroutesWhenArrivingAt waypoint: Waypoint) -> Bool {
return navigationComponents.allSatisfy { $0.navigationService(service, shouldPreventReroutesWhenArrivingAt: waypoint) }
}
public func navigationServiceShouldDisableBatteryMonitoring(_ service: NavigationService) -> Bool {
return navigationComponents.allSatisfy { $0.navigationServiceShouldDisableBatteryMonitoring(service) }
}
public func navigationServiceDidChangeAuthorization(_ service: NavigationService, didChangeAuthorizationFor locationManager: CLLocationManager) {
if #available(iOS 14.0, *), locationManager.accuracyAuthorization == .reducedAccuracy {
let title = NSLocalizedString("ENABLE_PRECISE_LOCATION", bundle: .mapboxNavigation, value: "Enable precise location to navigate", comment: "Label indicating precise location is off and needs to be turned on to navigate")
showStatus(title: title, spinner: false, duration: 20, animated: true, interactive: false)
navigationMapView?.reducedAccuracyActivatedMode = true
} else {
// Fallback on earlier versions
navigationMapView?.reducedAccuracyActivatedMode = false
return
}
}
// MARK: - Building Extrusion Highlighting methods
private func attemptToHighlightBuildings(_ progress: RouteProgress, with location: CLLocation) {
// In case if distance was fully covered - do nothing.
// FIXME: This check prevents issue which leads to highlighting random buildings after arrival to final destination.
// At the same time this check will prevent building highlighting in case of arrival in overview mode/high altitude.
if progress.fractionTraveled >= 1.0 { return }
if waypointStyle == .annotation { return }
if currentLeg != progress.currentLeg {
currentLeg = progress.currentLeg
passedApproachingDestinationThreshold = false
foundAllBuildings = false
}
if !passedApproachingDestinationThreshold, progress.currentLegProgress.distanceRemaining < approachingDestinationThreshold {
passedApproachingDestinationThreshold = true
}
if !foundAllBuildings, passedApproachingDestinationThreshold, let currentLegWaypoint = progress.currentLeg.destination?.targetCoordinate {
navigationMapView?.highlightBuildings(at: [currentLegWaypoint], in3D: waypointStyle == .extrudedBuilding ? true : false, completion: { (found) in
self.foundAllBuildings = found
})
}
}
}
// MARK: - StyleManagerDelegate
extension NavigationViewController: StyleManagerDelegate {
func roadName(at location: CLLocation) -> String? {
guard let roadName = delegate?.navigationViewController(self, roadNameAt: location) else {
return nil
}
return roadName
}
public func location(for styleManager: StyleManager) -> CLLocation? {
if let location = navigationService.router.location {
return location
} else if let firstCoord = route.shape?.coordinates.first {
return CLLocation(latitude: firstCoord.latitude, longitude: firstCoord.longitude)
} else {
return nil
}
}
public func styleManager(_ styleManager: StyleManager, didApply style: Style) {
updateMapStyle(style)
}
private func updateMapStyle(_ style: Style) {
if navigationMapView?.mapView.style.uri.rawValue != style.mapStyleURL {
navigationMapView?.mapView.style.uri = StyleURI.custom(url: style.mapStyleURL)
}
currentStatusBarStyle = style.statusBarStyle ?? .default
setNeedsStatusBarAppearanceUpdate()
}
public func styleManagerDidRefreshAppearance(_ styleManager: StyleManager) {
// TODO: Implement the ability to reload style.
}
}
// MARK: - TopBannerViewController methods
extension NavigationViewController {
// MARK: StatusView action related methods
@objc func didChangeSpeed(_ statusView: StatusView) {
let displayValue = 1+min(Int(9 * statusView.value), 8)
statusView.showSimulationStatus(speed: displayValue)
navigationService.simulationSpeedMultiplier = Double(displayValue)
}
}
// MARK: - TopBannerViewControllerDelegate methods
extension NavigationViewController: TopBannerViewControllerDelegate {
public func topBanner(_ banner: TopBannerViewController, didSwipeInDirection direction: UISwipeGestureRecognizer.Direction) {
let progress = navigationService.routeProgress
let route = progress.route
switch direction {
case .up where banner.isDisplayingSteps:
banner.dismissStepsTable()
case .down where !banner.isDisplayingSteps:
banner.displayStepsTable()
if banner.isDisplayingPreviewInstructions {
cameraController?.recenter(self)
}
default:
break
}
if !banner.isDisplayingSteps {
switch (direction, UIApplication.shared.userInterfaceLayoutDirection) {
case (.right, .leftToRight), (.left, .rightToLeft):
guard let currentStepIndex = banner.currentPreviewStep?.1 else { return }
let remainingSteps = progress.remainingSteps
let prevStepIndex = currentStepIndex.advanced(by: -1)
guard prevStepIndex >= 0 else { return }
let prevStep = remainingSteps[prevStepIndex]
preview(step: prevStep, in: banner, remaining: remainingSteps, route: route)
case (.left, .leftToRight), (.right, .rightToLeft):
let remainingSteps = navigationService.router.routeProgress.remainingSteps
let currentStepIndex = banner.currentPreviewStep?.1
let nextStepIndex = currentStepIndex?.advanced(by: 1) ?? 0
guard nextStepIndex < remainingSteps.count else { return }
let nextStep = remainingSteps[nextStepIndex]
preview(step: nextStep, in: banner, remaining: remainingSteps, route: route)
default:
break
}
}
}
public func preview(step: RouteStep, in banner: TopBannerViewController, remaining: [RouteStep], route: Route, animated: Bool = true) {
guard let leg = route.leg(containing: step) else { return }
guard let legIndex = route.legs.firstIndex(of: leg) else { return }
guard let stepIndex = leg.steps.firstIndex(of: step) else { return }
let legProgress = RouteLegProgress(leg: leg, stepIndex: stepIndex)
guard let upcomingStep = legProgress.upcomingStep else { return }
let previewBanner: CompletionHandler = {
banner.preview(step: legProgress.currentStep,
maneuverStep: upcomingStep,
distance: legProgress.currentStep.distance,
steps: remaining)
}
cameraController?.center(on: upcomingStep,
route: route,
legIndex: legIndex,
stepIndex: stepIndex + 1,
animated: animated,
completion: previewBanner)
}
public func topBanner(_ banner: TopBannerViewController, didSelect legIndex: Int, stepIndex: Int, cell: StepTableViewCell) {
let progress = navigationService.routeProgress
let legProgress = RouteLegProgress(leg: progress.route.legs[legIndex], stepIndex: stepIndex)
let step = legProgress.currentStep
self.preview(step: step, in: banner, remaining: progress.remainingSteps, route: progress.route, animated: false)
banner.dismissStepsTable()
}
public func topBanner(_ banner: TopBannerViewController, didDisplayStepsController: StepsViewController) {
cameraController?.recenter(self)
}
}
// MARK: - BottomBannerViewControllerDelegate
// Handling cancel action in new Bottom Banner container.
extension NavigationViewController: BottomBannerViewControllerDelegate {
public func didTapCancel(_ sender: Any) {
handleCancelAction()
}
}
// MARK: - CarPlayConnectionObserver
extension NavigationViewController: CarPlayConnectionObserver {
public func didConnectToCarPlay() {
navigationComponents.compactMap({$0 as? CarPlayConnectionObserver}).forEach {
$0.didConnectToCarPlay()
}
}
public func didDisconnectFromCarPlay() {
navigationComponents.compactMap({$0 as? CarPlayConnectionObserver}).forEach {
$0.didDisconnectFromCarPlay()
}
}
}
// MARK: - NavigationMapViewDelegate methods