-
Notifications
You must be signed in to change notification settings - Fork 327
Expand file tree
/
Copy pathNavigationService.swift
More file actions
848 lines (705 loc) · 38.9 KB
/
Copy pathNavigationService.swift
File metadata and controls
848 lines (705 loc) · 38.9 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
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
import UIKit
import CoreLocation
import MapboxDirections
import Turf
/**
A navigation service coordinates various nonvisual components that track the user as they navigate along a predetermined route. You use `MapboxNavigationService`, which conforms to this protocol, either as part of `NavigationViewController` or by itself as part of a custom user interface. A navigation service calls methods on its `delegate`, which conforms to the `NavigationServiceDelegate` protocol, whenever significant events or decision points occur along the route.
A navigation service controls a `NavigationLocationManager` for determining the user’s location, a `Router` that tracks the user’s progress along the route, a `MapboxRoutingProvider` service for calculating new routes (only used when rerouting), and a `NavigationEventsManager` for sending telemetry events related to navigation or user feedback.
`NavigationViewController` comes with a `MapboxNavigationService` by default. You may override it to customize the `MapboxRoutingProvider`'s source service or simulation mode. After creating the navigation service, pass it into `NavigationOptions(styles:navigationService:voiceController:topBanner:bottomBanner:)`, then pass that object into `NavigationViewController(for:options:)`.
If you use a navigation service by itself, outside of `NavigationViewController`, call `start()` when the user is ready to begin navigating along the route.
*/
public protocol NavigationService: CLLocationManagerDelegate, RouterDataSource, ActiveNavigationEventsManagerDataSource {
/**
The location manager for the service. This will be the object responsible for notifying the service of GPS updates.
*/
var locationManager: NavigationLocationManager { get }
/**
A reference to a MapboxDirections service. Used for rerouting.
*/
@available(*, deprecated, message: "Use `customRoutingProvider` instead. If navigation service was not initialized using `Directions` object - this property is unused and ignored.")
var directions: Directions { get }
/**
`RoutingProvider`, used to create a route during refreshing or rerouting.
*/
@available(*, deprecated, message: "Use `customRoutingProvider` instead. Nullable value now corresponds to SDK default behavior.")
var routingProvider: RoutingProvider { get }
/**
Custom `RoutingProvider`, used to create a route during refreshing or rerouting.
*/
var customRoutingProvider: RoutingProvider? { get }
/**
Credentials data, used to authorize server requests.
*/
var credentials: Credentials { get }
/**
The router object that tracks the user’s progress as they travel along a predetermined route.
*/
var router: Router { get }
/**
The events manager, responsible for all telemetry.
*/
var eventsManager: NavigationEventsManager { get }
/**
The route along which the user is expected to travel.
If you want to update the route, use `Router.updateRoute(with:routeOptions:completion:)` method from `router`.
*/
var route: Route { get }
/**
The `RouteResponse` object containing active route, plus its index in this `RouteResponse`, if applicable.
If you want to update the route, use `Router.updateRoute(with:routeOptions:completion:)` method from `router`.
*/
var indexedRouteResponse: IndexedRouteResponse { get }
/**
The simulation mode of the service.
*/
var simulationMode: SimulationMode { get set }
/**
The simulation speed-multiplier. Modify this if you desire accelerated simulation.
*/
var simulationSpeedMultiplier: Double { get set }
/**
The Amount of time the service will wait until it begins simulation in a poor GPS scenerio. Defaults to 2.5 seconds.
*/
var poorGPSPatience: Double { get set }
/**
The navigation service’s delegate, which is informed of significant events and decision points along the route.
To synchronize your application’s state with the turn-by-turn navigation experience, set this property before starting the navigation session.
*/
var delegate: NavigationServiceDelegate? { get set }
/**
Starts the navigation service.
*/
func start()
/**
Stops the navigation service. You may call `start()` after calling `stop()`.
*/
func stop()
/**
Ends the navigation session. Used when arriving at destination.
*/
func endNavigation(feedback: EndOfRouteFeedback?)
/**
Interrogates the navigationService as to whether or not the passed-in location is in a tunnel.
*/
func isInTunnel(at location: CLLocation, along progress: RouteProgress) -> Bool
}
/**
A concrete implementation of the `NavigationService` protocol.
`NavigationViewController` comes with a `MapboxNavigationService` by default. You may override it to customize the `Directions` service or simulation mode. After creating the navigation service, pass it into `NavigationOptions(styles:navigationService:voiceController:topBanner:bottomBanner:)`, then pass that object into `NavigationViewController(for:options:)`.
If you use a navigation service by itself, outside of `NavigationViewController`, call `start()` when the user is ready to begin navigating along the route.
*/
public class MapboxNavigationService: NSObject, NavigationService {
typealias DefaultRouter = RouteController
// MARK: Simulating Traversing
/**
The default time interval before beginning simulation when the `.onPoorGPS` or `.inTunnels` simulation options are enabled.
*/
static let defaultPoorGPSPatience: Double = 2.5 //seconds
/**
The Amount of time the service will wait until it begins simulation in a poor GPS scenerio. Defaults to 2.5 seconds.
*/
public var poorGPSPatience: Double = defaultPoorGPSPatience {
didSet {
poorGPSTimer.countdownInterval = poorGPSPatience.dispatchInterval
}
}
/**
The simulation mode of the service.
*/
public var simulationMode: SimulationMode {
didSet {
switch simulationMode {
case .always:
simulate()
case .onPoorGPS, .inTunnels:
poorGPSTimer.arm()
case .never:
poorGPSTimer.disarm()
endSimulation(intent: .manual)
}
}
}
/**
The simulation speed multiplier. If you desire the simulation to go faster than real-time, increase this value.
*/
public var simulationSpeedMultiplier: Double {
get {
guard simulationMode == .always else { return 1.0 }
return simulatedLocationSource?.speedMultiplier ?? 1.0
}
set {
guard simulationMode == .always else { return }
_simulationSpeedMultiplier = newValue
simulatedLocationSource?.speedMultiplier = newValue
let simulationState: SimulationState = isSimulating ? .inSimulation : .notInSimulation
announceSimulationDidChange(simulationState)
}
}
var poorGPSTimer: DispatchTimer { _poorGPSTimer! }
private var _poorGPSTimer: DispatchTimer?
private var isSimulating: Bool { return simulatedLocationSource != nil }
private var _simulationSpeedMultiplier: Double = 1.0
private func simulate(intent: SimulationIntent = .manual) {
guard !isSimulating else {
announceSimulationDidChange(.inSimulation)
return
}
let progress = router.routeProgress
delegate?.navigationService(self, willBeginSimulating: progress, becauseOf: intent)
announceSimulationDidChange(.willBeginSimulation)
simulatedLocationSource = SimulatedLocationManager(routeProgress: progress)
simulatedLocationSource?.delegate = self
simulatedLocationSource?.speedMultiplier = _simulationSpeedMultiplier
simulatedLocationSource?.startUpdatingLocation()
simulatedLocationSource?.startUpdatingHeading()
delegate?.navigationService(self, didBeginSimulating: progress, becauseOf: intent)
announceSimulationDidChange(.didBeginSimulation)
}
private func endSimulation(intent: SimulationIntent = .manual) {
guard isSimulating else {
announceSimulationDidChange(.notInSimulation)
return
}
let progress = router.routeProgress
delegate?.navigationService(self, willEndSimulating: progress, becauseOf: intent)
announceSimulationDidChange(.willEndSimulation)
simulatedLocationSource?.stopUpdatingLocation()
simulatedLocationSource?.stopUpdatingHeading()
simulatedLocationSource?.delegate = nil
simulatedLocationSource = nil
delegate?.navigationService(self, didEndSimulating: progress, becauseOf: intent)
announceSimulationDidChange(.didEndSimulation)
}
private func announceSimulationDidChange(_ simulationState: SimulationState) {
let userInfo: [NotificationUserInfoKey: Any] = [
NotificationUserInfoKey.simulationStateKey: simulationState,
NotificationUserInfoKey.simulatedSpeedMultiplierKey: _simulationSpeedMultiplier
]
NotificationCenter.default.post(name: .navigationServiceSimulationDidChange, object: self, userInfo: userInfo)
}
private func resetGPSCountdown() {
//Sanity check: if we're not on this mode, we have no business here.
guard simulationMode == .onPoorGPS || simulationMode == .inTunnels else { return }
// Immediately end simulation if it is occuring.
if isSimulating {
endSimulation(intent: .poorGPS)
}
// Reset the GPS countdown.
poorGPSTimer.reset()
}
// MARK: Starting and Stopping Navigation
/**
Starts navigation service.
Whenever navigation service starts billing session is resumed. For more info regarding billing,
read the [Pricing Guide](https://docs.mapbox.com/ios/beta/navigation/guides/pricing/).
*/
public func start() {
// Feed the first location to the router if router doesn't have a location yet. See #1790, #3237 for reference.
if router.location == nil {
if let currentLocation = locationManager.location {
router.locationManager?(nativeLocationSource, didUpdateLocations: [
currentLocation
])
}
else if let coordinate = route.shape?.coordinates.first { // fallback to simulated location.
router.locationManager?(nativeLocationSource, didUpdateLocations: [
CLLocation(coordinate: coordinate,
altitude: -1,
horizontalAccuracy: -1,
verticalAccuracy: -1,
course: -1,
speed: 0,
timestamp: Date())
])
}
}
nativeLocationSource.startUpdatingHeading()
nativeLocationSource.startUpdatingLocation()
if simulationMode == .always {
simulate()
}
eventsManager.sendRouteRetrievalEvent()
router.delegate = self
// In case if billing session is already running - do nothing.
if let routeController = router as? RouteController,
BillingHandler.shared.sessionState(uuid: routeController.sessionUUID) != .running {
BillingHandler.shared.resumeBillingSession(with: routeController.sessionUUID)
}
}
/**
Stops navigation service. Navigation service can be resumed by calling `start()` after calling
`stop()`.
Whenever navigation service stops billing session is paused. For more info regarding billing,
read the [Pricing Guide](https://docs.mapbox.com/ios/beta/navigation/guides/pricing/).
*/
public func stop() {
nativeLocationSource.stopUpdatingHeading()
nativeLocationSource.stopUpdatingLocation()
if [.always, .onPoorGPS, .inTunnels].contains(simulationMode) {
endSimulation()
}
poorGPSTimer.disarm()
router.delegate = nil
// Navigator should also be paused to prevent further location updates. In case if billing
// session is not running anymore - do nothing.
if let routeController = router as? RouteController,
BillingHandler.shared.sessionState(uuid: routeController.sessionUUID) == .running {
BillingHandler.shared.pauseBillingSession(with: routeController.sessionUUID)
}
}
public func endNavigation(feedback: EndOfRouteFeedback? = nil) {
eventsManager.sendCancelEvent(rating: feedback?.rating, comment: feedback?.comment)
stop()
}
/**
Intializes a new `NavigationService`.
- parameter routeResponse: `RouteResponse` object, containing selection of routes to follow.
- parameter routeIndex: The index of the route within the original `RouteResponse` object.
- parameter routeOptions: The route options used to get the route.
- parameter directions: The Directions object that created `route`. If this argument is omitted, the shared value of `NavigationSettings.directions` will be used.
- parameter locationSource: An optional override for the default `NaviationLocationManager`.
- parameter eventsManagerType: An optional events manager type to use while tracking the route.
- parameter simulationMode: The simulation mode desired.
- parameter routerType: An optional router type to use for traversing the route.
*/
@available(*, deprecated, renamed: "init(indexedRouteResponse:customRoutingProvider:credentials:locationSource:eventsManagerType:simulating:routerType:customActivityType:)")
public convenience init(routeResponse: RouteResponse,
routeIndex: Int,
routeOptions: RouteOptions,
directions: Directions? = nil,
locationSource: NavigationLocationManager? = nil,
eventsManagerType: NavigationEventsManager.Type? = nil,
simulating simulationMode: SimulationMode? = nil,
routerType: Router.Type? = nil) {
self.init(routeResponse: routeResponse,
routeIndex: routeIndex,
routeOptions: routeOptions,
customRoutingProvider: directions ?? Directions.shared,
credentials: directions?.credentials ?? NavigationSettings.shared.directions.credentials,
locationSource: locationSource,
eventsManagerType: eventsManagerType,
simulating: simulationMode,
routerType: routerType)
}
/**
Intializes a new `NavigationService`.
- parameter routeResponse: `RouteResponse` object, containing selection of routes to follow.
- parameter routeIndex: The index of the route within the original `RouteResponse` object.
- parameter routeOptions: The route options used to get the route.
- parameter routingProvider: `RoutingProvider`, used to create a route during refreshing or rerouting.
- parameter credentials: Credentials to authorize additional data requests throughout the route.
- parameter locationSource: An optional override for the default `NaviationLocationManager`.
- parameter eventsManagerType: An optional events manager type to use while tracking the route.
- parameter simulationMode: The simulation mode desired.
- parameter routerType: An optional router type to use for traversing the route.
*/
@available(*, deprecated, renamed: "init(indexedRouteResponse:customRoutingProvider:credentials:locationSource:eventsManagerType:simulating:routerType:customActivityType:)")
public convenience init(routeResponse: RouteResponse,
routeIndex: Int,
routeOptions: RouteOptions,
routingProvider: RoutingProvider,
credentials: Credentials,
locationSource: NavigationLocationManager? = nil,
eventsManagerType: NavigationEventsManager.Type? = nil,
simulating simulationMode: SimulationMode? = nil,
routerType: Router.Type? = nil) {
self.init(routeResponse: routeResponse,
routeIndex: routeIndex,
routeOptions: routeOptions,
customRoutingProvider: routingProvider,
credentials: credentials,
locationSource: locationSource,
eventsManagerType: eventsManagerType,
simulating: simulationMode,
routerType: routerType)
}
/**
Intializes a new `NavigationService`.
- parameter routeResponse: `RouteResponse` object, containing selection of routes to follow.
- parameter routeIndex: The index of the route within the original `RouteResponse` object.
- parameter routeOptions: The route options used to get the route.
- parameter customRoutingProvider: Custom `RoutingProvider`, used to create a route during refreshing or rerouting.
- parameter credentials: Credentials to authorize additional data requests throughout the route.
- parameter locationSource: An optional override for the default `NaviationLocationManager`.
- parameter eventsManagerType: An optional events manager type to use while tracking the route.
- parameter simulationMode: The simulation mode desired.
- parameter routerType: An optional router type to use for traversing the route.
- parameter customActivityType: Custom `CLActivityType` to be used for location updates. If not specified, SDK will pick it automatically for current navigation profile.
*/
@available(*, deprecated, renamed: "init(indexedRouteResponse:customRoutingProvider:credentials:locationSource:eventsManagerType:simulating:routerType:customActivityType:)")
required public convenience init(routeResponse: RouteResponse,
routeIndex: Int,
routeOptions: RouteOptions,
customRoutingProvider: RoutingProvider? = nil,
credentials: Credentials,
locationSource: NavigationLocationManager? = nil,
eventsManagerType: NavigationEventsManager.Type? = nil,
simulating simulationMode: SimulationMode? = nil,
routerType: Router.Type? = nil,
customActivityType: CLActivityType? = nil) {
self.init(indexedRouteResponse: .init(routeResponse: routeResponse,
routeIndex: routeIndex),
customRoutingProvider: customRoutingProvider,
credentials: credentials,
locationSource: locationSource,
eventsManagerType: eventsManagerType,
simulating: simulationMode,
routerType: routerType,
customActivityType: customActivityType)
}
/**
Intializes a new `NavigationService`.
- parameter indexedRouteResponse: `IndexedRouteResponse` object, containing selection of routes to follow.
- parameter customRoutingProvider: Custom `RoutingProvider`, used to create a route during refreshing or rerouting.
- parameter credentials: Credentials to authorize additional data requests throughout the route.
- parameter locationSource: An optional override for the default `NaviationLocationManager`.
- parameter eventsManagerType: An optional events manager type to use while tracking the route.
- parameter simulationMode: The simulation mode desired.
- parameter routerType: An optional router type to use for traversing the route.
*/
required public init(indexedRouteResponse: IndexedRouteResponse,
customRoutingProvider: RoutingProvider? = nil,
credentials: Credentials,
locationSource: NavigationLocationManager? = nil,
eventsManagerType: NavigationEventsManager.Type? = nil,
simulating simulationMode: SimulationMode? = nil,
routerType: Router.Type? = nil,
customActivityType: CLActivityType? = nil) {
nativeLocationSource = locationSource ?? NavigationLocationManager()
self.credentials = credentials
self.simulationMode = simulationMode ?? .inTunnels
super.init()
resumeNotifications()
_poorGPSTimer = DispatchTimer(countdown: poorGPSPatience.dispatchInterval) { [weak self] in
guard let self = self,
self.simulationMode == .onPoorGPS ||
(self.simulationMode == .inTunnels && self.isInTunnel(at: self.router.location!, along: self.routeProgress)) else { return }
self.simulate(intent: .poorGPS)
}
let routerType = routerType ?? DefaultRouter.self
_router = routerType.init(indexedRouteResponse: indexedRouteResponse,
customRoutingProvider: customRoutingProvider,
dataSource: self)
let options = indexedRouteResponse.validatedRouteOptions
NavigationSettings.shared.distanceUnit = .init(options.distanceMeasurementSystem)
let eventType = eventsManagerType ?? NavigationEventsManager.self
_eventsManager = eventType.init(activeNavigationDataSource: self,
accessToken: self.credentials.accessToken)
locationManager.activityType = customActivityType ?? options.activityType
bootstrapEvents()
router.delegate = self
nativeLocationSource.delegate = self
checkForUpdates()
checkForLocationUsageDescription()
}
/**
Intializes a new `NavigationService` for replaying a session from provided `History`.
- parameter history: `History` object, containing initial route and location trace to be replayed.
- parameter customRoutingProvider: Custom `RoutingProvider`, used to create a route during refreshing or rerouting.
- parameter credentials: Credentials to authorize additional data requests throughout the route.
- parameter eventsManagerType: An optional events manager type to use while tracking the route.
- parameter routerType: An optional router type to use for traversing the route.
- returns `nil` if provided `historyFileDump` does not contain valid initial route.
*/
public convenience init?(history: History,
customRoutingProvider: RoutingProvider? = nil,
credentials: Credentials,
eventsManagerType: NavigationEventsManager.Type? = nil,
routerType: Router.Type? = nil,
customActivityType: CLActivityType? = nil) {
guard let routeResponse = history.initialRoute else {
return nil
}
self.init(indexedRouteResponse: routeResponse,
customRoutingProvider: customRoutingProvider,
credentials: credentials,
locationSource: ReplayLocationManager(history: history),
eventsManagerType: eventsManagerType,
routerType: routerType,
customActivityType: customActivityType)
}
deinit {
suspendNotifications()
eventsManager.withBackupDataSource(active: self, passive: nil) {
endNavigation()
}
nativeLocationSource.delegate = nil
simulatedLocationSource?.delegate = nil
}
private func bootstrapEvents() {
eventsManager.activeNavigationDataSource = self
eventsManager.resetSession()
}
func resumeNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminate(_:)), name: UIApplication.willTerminateNotification, object: nil)
}
func suspendNotifications() {
NotificationCenter.default.removeObserver(self)
}
@objc private func applicationWillTerminate(_ notification: NSNotification) {
endNavigation()
}
// MARK: Managing Location
/**
The active location manager. Returns the location simulator if we're actively simulating, otherwise it returns the native location manager.
*/
public var locationManager: NavigationLocationManager {
return simulatedLocationSource ?? nativeLocationSource
}
/**
The native location source. This is a `NavigationLocationManager` by default, but can be overridden with a custom location manager at initalization.
*/
private var nativeLocationSource: NavigationLocationManager
/**
The active location simulator. Only used during `SimulationOption.always`, `SimluatedLocationManager.onPoorGPS` and `SimluatedLocationManager.inTunnels`. If there is no simulation active, this property is `nil`.
*/
private var simulatedLocationSource: SimulatedLocationManager?
/**
A reference to a MapboxDirections service. Used for rerouting.
*/
@available(*, deprecated, message: "Use `routingProvider` instead. If navigation service was not initialized using `Directions` object - this property is unused and ignored.")
public lazy var directions: Directions = self.routingProvider as? Directions ?? NavigationSettings.shared.directions
/**
Custom `RoutingProvider`, used to create a route during refreshing or rerouting.
*/
@available(*, deprecated, message: "Use `customRoutingProvider` instead. This property will be equal to `customRoutingProvider` if that is provided or a `MapboxRoutingProvider` instance otherwise.")
public var routingProvider: RoutingProvider {
router.routingProvider
}
/**
Custom `RoutingProvider`, used to create a route during refreshing or rerouting.
If set to `nil` - default Mapbox implementation will be used.
*/
public var customRoutingProvider: RoutingProvider? {
router.customRoutingProvider
}
/**
Credentials data, used to authorize server requests.
*/
public var credentials: Credentials
// MARK: Managing Route-Related Data
/**
The `NavigationService` delegate. Wraps `RouterDelegate` messages.
*/
public weak var delegate: NavigationServiceDelegate?
/**
The active router. By default, a `RouteController`.
*/
public var router: Router { _router! }
/**
The events manager. Sends telemetry back to the Mapbox platform.
*/
public var eventsManager: NavigationEventsManager { _eventsManager! }
public var route: Route {
router.route
}
public var indexedRouteResponse: IndexedRouteResponse {
router.indexedRouteResponse
}
private var _router: Router?
private var _eventsManager: NavigationEventsManager?
/**
Determines if a location is within a tunnel.
- parameter location: The location to test.
- parameter progress: the RouteProgress model that contains the route geometry.
*/
public func isInTunnel(at location: CLLocation, along progress: RouteProgress) -> Bool {
return TunnelAuthority.isInTunnel(at: location, along: progress)
}
public func updateRoute(with indexedRouteResponse: IndexedRouteResponse,
routeOptions: RouteOptions?,
completion: ((Bool) -> Void)?) {
router.updateRoute(with: indexedRouteResponse, routeOptions: routeOptions, completion: completion)
}
}
extension MapboxNavigationService: CLLocationManagerDelegate {
// MARK: Handling LocationManager Output
public func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
// Check if device orientation has changed and inform the location provider accordingly.
updateHeadingForCurrentDeviceOrientation()
router.locationManager?(manager, didUpdateHeading: newHeading)
}
public func updateHeadingForCurrentDeviceOrientation() {
var orientation: CLDeviceOrientation
switch UIDevice.current.orientation {
case .landscapeLeft:
orientation = .landscapeRight
case .landscapeRight:
orientation = .landscapeLeft
default:
orientation = .portrait
}
if locationManager.headingOrientation != orientation {
locationManager.headingOrientation = orientation
}
}
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//If we're always simulating, make sure this is a simulated update.
if simulationMode == .always, manager != simulatedLocationSource { return }
//update the events manager with the received locations
eventsManager.record(locations)
//sanity check: make sure the update actually contains a location
guard let location = locations.last else { return }
//If this is a good organic update, reset the timer.
if simulationMode == .onPoorGPS || simulationMode == .inTunnels,
manager == nativeLocationSource,
location.isQualified {
//If the timer is disarmed, arm it. This is a good update.
if poorGPSTimer.state == .disarmed, location.isQualifiedForStartingRoute {
poorGPSTimer.arm()
}
//pass this good update onto the poor GPS timer mechanism.
resetGPSCountdown()
}
//Finally, pass the update onto the router.
router.locationManager?(manager, didUpdateLocations: locations)
}
public func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
if #available(iOS 14.0, *) {
let info: [NotificationUserInfoKey: Any] = [
.locationAuthorizationKey: manager.value(forKey: "accuracyAuthorization") ?? 0
]
NotificationCenter.default.post(name: .locationAuthorizationDidChange, object: manager, userInfo: info)
delegate?.navigationServiceDidChangeAuthorization(self, didChangeAuthorizationFor: manager)
} else {
// Fallback on earlier versions
return
}
}
}
extension MapboxNavigationService: RouterDelegate {
typealias Default = RouteController.DefaultBehavior
//MARK: RouteControllerDelegate Implementation
public func router(_ router: Router, willRerouteFrom location: CLLocation) {
//save any progress made by the router until now
eventsManager.enqueueRerouteEvent()
eventsManager.incrementDistanceTraveled(by: router.routeProgress.distanceTraveled)
//notify our consumer
delegate?.navigationService(self, willRerouteFrom: location)
}
public func router(_ router: Router, modifiedOptionsForReroute options: RouteOptions) -> RouteOptions {
return delegate?.navigationService(self, modifiedOptionsForReroute: options) ?? options
}
public func router(_ router: Router, didRerouteAlong route: Route, at location: CLLocation?, proactive: Bool) {
//notify the events manager that the route has changed
eventsManager.reportReroute(progress: router.routeProgress, proactive: proactive)
//update the route progress model of the simulated location manager, if applicable.
simulatedLocationSource?.route = router.route
//notify our consumer
delegate?.navigationService(self, didRerouteAlong: route, at: location, proactive: proactive)
}
public func router(_ router: Router, didFailToRerouteWith error: Error) {
delegate?.navigationService(self, didFailToRerouteWith: error)
}
public func router(_ router: Router, didRefresh routeProgress: RouteProgress) {
delegate?.navigationService(self, didRefresh: routeProgress)
}
public func router(_ router: Router, didUpdate progress: RouteProgress, with location: CLLocation, rawLocation: CLLocation) {
//notify the events manager of the progress update
eventsManager.update(progress: progress)
//pass the update on to consumers
delegate?.navigationService(self, didUpdate: progress, with: location, rawLocation: rawLocation)
}
public func router(_ router: Router, didPassVisualInstructionPoint instruction: VisualInstructionBanner, routeProgress: RouteProgress) {
delegate?.navigationService(self, didPassVisualInstructionPoint: instruction, routeProgress: routeProgress)
}
public func router(_ router: Router, didPassSpokenInstructionPoint instruction: SpokenInstruction, routeProgress: RouteProgress) {
delegate?.navigationService(self, didPassSpokenInstructionPoint: instruction, routeProgress: routeProgress)
}
public func router(_ router: Router, shouldRerouteFrom location: CLLocation) -> Bool {
return delegate?.navigationService(self, shouldRerouteFrom: location) ?? Default.shouldRerouteFromLocation
}
public func router(_ router: Router, shouldDiscard location: CLLocation) -> Bool {
return delegate?.navigationService(self, shouldDiscard: location) ?? Default.shouldDiscardLocation
}
public func router(_ router: Router, willArriveAt waypoint: Waypoint, after remainingTimeInterval: TimeInterval, distance: CLLocationDistance) {
delegate?.navigationService(self, willArriveAt: waypoint, after: remainingTimeInterval, distance: distance)
}
public func router(_ router: Router, didArriveAt waypoint: Waypoint) -> Bool {
//Notify the events manager that we've arrived at a waypoint
if router.routeProgress.remainingWaypoints.count <= 1 {
eventsManager.arriveAtDestination()
} else {
eventsManager.arriveAtWaypoint()
}
let shouldAutomaticallyAdvance = delegate?.navigationService(self, didArriveAt: waypoint) ?? Default.didArriveAtWaypoint
if !shouldAutomaticallyAdvance {
stop()
}
return shouldAutomaticallyAdvance
}
public func router(_ router: Router, shouldPreventReroutesWhenArrivingAt waypoint: Waypoint) -> Bool {
return delegate?.navigationService(self, shouldPreventReroutesWhenArrivingAt: waypoint) ?? Default.shouldPreventReroutesWhenArrivingAtWaypoint
}
public func routerShouldDisableBatteryMonitoring(_ router: Router) -> Bool {
return delegate?.navigationServiceShouldDisableBatteryMonitoring(self) ?? Default.shouldDisableBatteryMonitoring
}
public func router(_ router: Router, didUpdateAlternatives updatedAlternatives: [AlternativeRoute], removedAlternatives: [AlternativeRoute]) {
delegate?.navigationService(self, didUpdateAlternatives: updatedAlternatives, removedAlternatives: removedAlternatives)
}
public func router(_ router: Router, didFailToUpdateAlternatives error: AlternativeRouteError) {
delegate?.navigationService(self, didFailToUpdateAlternatives: error)
}
public func router(_ router: Router, didSwitchToCoincidentOnlineRoute coincideRoute: Route) {
//update the route progress model of the simulated location manager, if applicable.
simulatedLocationSource?.route = router.route
delegate?.navigationService(self, didSwitchToCoincidentOnlineRoute: coincideRoute)
}
public func router(_ router: Router, willTakeAlternativeRoute route: Route, at location: CLLocation?) {
delegate?.navigationService(self, willTakeAlternativeRoute: route, at: location)
}
public func router(_ router: Router, didTakeAlternativeRouteAt location: CLLocation?) {
delegate?.navigationService(self, didTakeAlternativeRouteAt: location)
}
public func router(_ router: Router, didFailToTakeAlternativeRouteAt location: CLLocation?) {
delegate?.navigationService(self, didFailToTakeAlternativeRouteAt: location)
}
}
extension MapboxNavigationService {
//MARK: ActiveNavigationEventsManagerDataSource Logic
public var routeProgress: RouteProgress {
return router.routeProgress
}
public var desiredAccuracy: CLLocationAccuracy {
return locationManager.desiredAccuracy
}
}
extension MapboxNavigationService {
//MARK: RouterDataSource Implementation
public var locationManagerType: NavigationLocationManager.Type {
return type(of: locationManager)
}
}
private extension Double {
var dispatchInterval: DispatchTimeInterval {
let milliseconds = self * 1000.0 //milliseconds per second
let intMilliseconds = Int(milliseconds)
return .milliseconds(intMilliseconds)
}
}
private func checkForUpdates() {
#if TARGET_IPHONE_SIMULATOR
guard (NSClassFromString("XCTestCase") == nil) else { return } // Short-circuit when running unit tests
guard let version = Bundle.string(forMapboxCoreNavigationInfoDictionaryKey: "CFBundleShortVersionString") else { return }
let latestVersion = String(describing: version)
_ = URLSession.shared.dataTask(with: URL(string: "https://docs.mapbox.com/ios/navigation/latest_version.txt")!, completionHandler: { (data, response, error) in
if let _ = error { return }
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { return }
guard let data = data, let currentVersion = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .newlines) else { return }
if latestVersion != currentVersion {
let updateString = NSLocalizedString("UPDATE_AVAILABLE", bundle: .mapboxCoreNavigation, value: "Mapbox Navigation SDK for iOS version %@ is now available.", comment: "Inform developer an update is available")
Log.info(String.localizedStringWithFormat(updateString, latestVersion), "https://github.com/mapbox/mapbox-navigation-ios/releases/tag/v\(latestVersion)", category: .settings)
}
}).resume()
#endif
}
private func checkForLocationUsageDescription() {
guard let _ = Bundle.main.bundleIdentifier else {
return
}
if Bundle.main.locationWhenInUseUsageDescription == nil && Bundle.main.locationAlwaysAndWhenInUseUsageDescription == nil {
if UserDefaults.standard.object(forKey: "NSLocationWhenInUseUsageDescription") == nil && UserDefaults.standard.object(forKey: "NSLocationAlwaysAndWhenInUseUsageDescription") == nil {
preconditionFailure("This application’s Info.plist file must include a NSLocationWhenInUseUsageDescription. See https://developer.apple.com/documentation/corelocation for more information.")
}
}
}