diff --git a/.swiftformat b/.swiftformat index 4439b5cd..bbbddafa 100644 --- a/.swiftformat +++ b/.swiftformat @@ -54,7 +54,7 @@ --patternlet hoist --ranges spaced --redundanttype infer-locals-only ---self remove +--self insert --selfrequired --semicolons inline --shortoptionals except-properties diff --git a/MapboxCoreNavigation/CLLocation.swift b/MapboxCoreNavigation/CLLocation.swift index 25fdc46f..50ba693f 100644 --- a/MapboxCoreNavigation/CLLocation.swift +++ b/MapboxCoreNavigation/CLLocation.swift @@ -70,7 +70,7 @@ extension CLLocation { // MARK: - Route Snapping func snapped(to legProgress: RouteLegProgress) -> CLLocation? { - let coords = coordinates(for: legProgress) + let coords = self.coordinates(for: legProgress) guard let closest = Polyline(coords).closestCoordinate(to: coordinate) else { return nil } guard let calculatedCourseForLocationOnStep = interpolatedCourse(along: coords) else { return nil } @@ -79,7 +79,7 @@ extension CLLocation { let userCoordinate = closest.coordinate guard let firstCoordinate = legProgress.leg.steps.first?.coordinates?.first else { return nil } - guard shouldSnapCourse(toRouteWith: calculatedCourseForLocationOnStep, distanceToFirstCoordinateOnLeg: coordinate.distance(to: firstCoordinate)) else { return nil } + guard self.shouldSnapCourse(toRouteWith: calculatedCourseForLocationOnStep, distanceToFirstCoordinateOnLeg: coordinate.distance(to: firstCoordinate)) else { return nil } guard closest.distance <= (RouteControllerUserLocationSnappingDistance + horizontalAccuracy) else { return nil diff --git a/MapboxCoreNavigation/CoreFeedbackEvent.swift b/MapboxCoreNavigation/CoreFeedbackEvent.swift index 66ea1869..5935b87c 100644 --- a/MapboxCoreNavigation/CoreFeedbackEvent.swift +++ b/MapboxCoreNavigation/CoreFeedbackEvent.swift @@ -15,7 +15,7 @@ class CoreFeedbackEvent: Hashable { } func hash(into hasher: inout Hasher) { - hasher.combine(id) + hasher.combine(self.id) } static func == (lhs: CoreFeedbackEvent, rhs: CoreFeedbackEvent) -> Bool { diff --git a/MapboxCoreNavigation/DistanceFormatter.swift b/MapboxCoreNavigation/DistanceFormatter.swift index 81d68572..0f109a15 100644 --- a/MapboxCoreNavigation/DistanceFormatter.swift +++ b/MapboxCoreNavigation/DistanceFormatter.swift @@ -16,7 +16,7 @@ extension CLLocationDistance { // Returns the distance converted to yards var yards: Double { - feet / 3 + self.feet / 3 } // Returns the distance converted to kilometers @@ -43,15 +43,15 @@ extension CLLocationDistance { case .meter: return self case .kilometer: - return kilometers + return self.kilometers case .inch: - return feet * 12 + return self.feet * 12 case .foot: - return feet + return self.feet case .yard: - return yards + return self.yards case .mile: - return miles + return self.miles @unknown default: fatalError("Unknown unit") } @@ -67,7 +67,7 @@ struct RoundingTable { @available(iOS 10.0, *) func measurement(for distance: CLLocationDistance) -> Measurement { - switch unit { + switch self.unit { case .millimeter: return Measurement(value: distance.kilometers / 1e6, unit: .millimeters) case .centimeter: @@ -90,17 +90,17 @@ struct RoundingTable { } func localizedDistanceString(for distance: CLLocationDistance, using formatter: DistanceFormatter) -> String { - switch unit { + switch self.unit { case .mile: - formatter.string(fromValue: distance.miles, unit: unit) + formatter.string(fromValue: distance.miles, unit: self.unit) case .foot: - formatter.string(fromValue: distance.feet, unit: unit) + formatter.string(fromValue: distance.feet, unit: self.unit) case .yard: - formatter.string(fromValue: distance.yards, unit: unit) + formatter.string(fromValue: distance.yards, unit: self.unit) case .kilometer: - formatter.string(fromValue: distance.kilometers, unit: unit) + formatter.string(fromValue: distance.kilometers, unit: self.unit) default: - formatter.string(fromValue: distance, unit: unit) + formatter.string(fromValue: distance, unit: self.unit) } } } @@ -108,12 +108,12 @@ struct RoundingTable { let thresholds: [Threshold] func threshold(for distance: CLLocationDistance) -> Threshold { - for threshold in thresholds { + for threshold in self.thresholds { if distance < threshold.maximumDistance { return threshold } } - return thresholds.last! + return self.thresholds.last! } } @@ -155,28 +155,28 @@ open class DistanceFormatter: LengthFormatter { - parameter approximate: approximates the distances. */ @objc public init(approximate: Bool = false) { - approx = approximate + self.approx = approximate super.init() numberFormatter.locale = .nationalizedCurrent } public required init?(coder decoder: NSCoder) { - approx = decoder.decodeBool(forKey: "approximate") + self.approx = decoder.decodeBool(forKey: "approximate") super.init(coder: decoder) } override open func encode(with aCoder: NSCoder) { super.encode(with: aCoder) - aCoder.encode(approx, forKey: "approximate") + aCoder.encode(self.approx, forKey: "approximate") } func threshold(for distance: CLLocationDistance) -> RoundingTable.Threshold { if NavigationSettings.shared.usesMetric { - roundingTableMetric.threshold(for: distance) + self.roundingTableMetric.threshold(for: distance) } else if numberFormatter.locale.identifier == "en-GB" { - roundingTableUK.threshold(for: distance) + self.roundingTableUK.threshold(for: distance) } else { - roundingTableImperial.threshold(for: distance) + self.roundingTableImperial.threshold(for: distance) } } @@ -188,21 +188,21 @@ open class DistanceFormatter: LengthFormatter { @objc public func string(from distance: CLLocationDistance) -> String { numberFormatter.positivePrefix = "" numberFormatter.positiveSuffix = "" - numberFormatter.decimalSeparator = nonFractionalLengthFormatter.numberFormatter.decimalSeparator - numberFormatter.alwaysShowsDecimalSeparator = nonFractionalLengthFormatter.numberFormatter.alwaysShowsDecimalSeparator + numberFormatter.decimalSeparator = self.nonFractionalLengthFormatter.numberFormatter.decimalSeparator + numberFormatter.alwaysShowsDecimalSeparator = self.nonFractionalLengthFormatter.numberFormatter.alwaysShowsDecimalSeparator numberFormatter.usesSignificantDigits = false - return formattedDistance(distance) + return self.formattedDistance(distance) } @objc override open func string(fromMeters numberInMeters: Double) -> String { - string(from: numberInMeters) + self.string(from: numberInMeters) } func formattedDistance(_ distance: CLLocationDistance) -> String { let threshold = threshold(for: distance) numberFormatter.maximumFractionDigits = threshold.maximumFractionDigits numberFormatter.roundingIncrement = threshold.roundingIncrement as NSNumber - unit = threshold.unit + self.unit = threshold.unit return threshold.localizedDistanceString(for: distance, using: self) } @@ -212,7 +212,7 @@ open class DistanceFormatter: LengthFormatter { let threshold = threshold(for: distance) numberFormatter.maximumFractionDigits = threshold.maximumFractionDigits numberFormatter.roundingIncrement = threshold.roundingIncrement as NSNumber - unit = threshold.unit + self.unit = threshold.unit return threshold.measurement(for: distance) } @@ -228,7 +228,7 @@ open class DistanceFormatter: LengthFormatter { let string = string(from: distance) let attributedString = NSMutableAttributedString(string: string, attributes: attrs) - let convertedDistance = distance.converted(to: threshold(for: distance).unit) + let convertedDistance = distance.converted(to: self.threshold(for: distance).unit) if let quantityString = numberFormatter.string(from: convertedDistance as NSNumber) { // NSMutableAttributedString methods accept NSRange, not Range. let quantityRange = (string as NSString).range(of: quantityString) diff --git a/MapboxCoreNavigation/NavigationLocationManager.swift b/MapboxCoreNavigation/NavigationLocationManager.swift index 93fe588d..8c80596b 100644 --- a/MapboxCoreNavigation/NavigationLocationManager.swift +++ b/MapboxCoreNavigation/NavigationLocationManager.swift @@ -11,7 +11,7 @@ import UIKit open class NavigationLocationManager: CLLocationManager, NSCopying { public func copy(with zone: NSZone? = nil) -> Any { let copy = NavigationLocationManager() - copy.lastKnownLocation = lastKnownLocation + copy.lastKnownLocation = self.lastKnownLocation return copy } diff --git a/MapboxCoreNavigation/NavigationSettings.swift b/MapboxCoreNavigation/NavigationSettings.swift index 5cebf309..b1d345a4 100644 --- a/MapboxCoreNavigation/NavigationSettings.swift +++ b/MapboxCoreNavigation/NavigationSettings.swift @@ -36,7 +36,7 @@ public class NavigationSettings: NSObject { @objc public dynamic var distanceUnit: LengthFormatter.Unit = Locale.current.usesMetric ? .kilometer : .mile var usesMetric: Bool { - switch distanceUnit { + switch self.distanceUnit { case .kilometer: true case .mile: @@ -61,7 +61,7 @@ public class NavigationSettings: NSObject { override init() { super.init() - for property in properties { + for property in self.properties { guard let key = property.label else { continue } let val = UserDefaults.standard.object(forKey: key.prefixed) ?? value(forKey: key) setValue(val, forKey: key) @@ -79,7 +79,7 @@ public class NavigationSettings: NSObject { override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { var found = false - for property in properties { + for property in self.properties { guard let key = property.label else { continue } if key == keyPath { diff --git a/MapboxCoreNavigation/ReplayLocationManager.swift b/MapboxCoreNavigation/ReplayLocationManager.swift index 268c76e3..8a6b8f61 100644 --- a/MapboxCoreNavigation/ReplayLocationManager.swift +++ b/MapboxCoreNavigation/ReplayLocationManager.swift @@ -22,7 +22,7 @@ open class ReplayLocationManager: NavigationLocationManager { */ @objc public var locations: [CLLocation]! { didSet { - currentIndex = 0 + self.currentIndex = 0 } } @@ -40,34 +40,34 @@ open class ReplayLocationManager: NavigationLocationManager { } override open func startUpdatingLocation() { - startDate = Date() - tick() + self.startDate = Date() + self.tick() } override open func stopUpdatingLocation() { - startDate = nil - NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(tick), object: nil) + self.startDate = nil + NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.tick), object: nil) } @objc fileprivate func tick() { guard let startDate else { return } - let location = locations[currentIndex] + let location = self.locations[self.currentIndex] lastKnownLocation = location delegate?.locationManager?(self, didUpdateLocations: [location]) - NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(tick), object: nil) + NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.tick), object: nil) - if currentIndex < locations.count - 1 { - let nextLocation = locations[currentIndex + 1] - let interval = nextLocation.timestamp.timeIntervalSince(location.timestamp) / TimeInterval(speedMultiplier) + if self.currentIndex < self.locations.count - 1 { + let nextLocation = self.locations[self.currentIndex + 1] + let interval = nextLocation.timestamp.timeIntervalSince(location.timestamp) / TimeInterval(self.speedMultiplier) let intervalSinceStart = Date().timeIntervalSince(startDate) + interval - let actualInterval = nextLocation.timestamp.timeIntervalSince(locations.first!.timestamp) + let actualInterval = nextLocation.timestamp.timeIntervalSince(self.locations.first!.timestamp) let diff = min(max(0, intervalSinceStart - actualInterval), 0.9) // Don't try to resync more than 0.9 seconds per location update let syncedInterval = interval - diff - perform(#selector(tick), with: nil, afterDelay: syncedInterval) - currentIndex += 1 + perform(#selector(self.tick), with: nil, afterDelay: syncedInterval) + self.currentIndex += 1 } else { - currentIndex = 0 + self.currentIndex = 0 } } } diff --git a/MapboxCoreNavigation/RouteController.swift b/MapboxCoreNavigation/RouteController.swift index 32de0199..15b0b1ff 100644 --- a/MapboxCoreNavigation/RouteController.swift +++ b/MapboxCoreNavigation/RouteController.swift @@ -37,7 +37,7 @@ open class RouteController: NSObject, Router { @objc public var locationManager: NavigationLocationManager! { didSet { oldValue.delegate = nil - locationManager.delegate = self + self.locationManager.delegate = self } } @@ -79,9 +79,9 @@ open class RouteController: NSObject, Router { if let location = locationManager.location { userInfo[.locationKey] = location } - userInfo[.isProactiveKey] = didFindFasterRoute + userInfo[.isProactiveKey] = self.didFindFasterRoute NotificationCenter.default.post(name: .routeControllerDidReroute, object: self, userInfo: userInfo) - movementsAwayFromRoute = 0 + self.movementsAwayFromRoute = 0 } } @@ -138,7 +138,7 @@ open class RouteController: NSObject, Router { @objc(initWithRoute:directions:locationManager:) public init(along route: Route, directions: Directions = Directions.shared, locationManager: NavigationLocationManager = NavigationLocationManager()) { self.directions = directions - routeProgress = RouteProgress(route: route) + self.routeProgress = RouteProgress(route: route) self.locationManager = locationManager self.locationManager.activityType = route.routeOptions.activityType UIDevice.current.isBatteryMonitoringEnabled = true @@ -146,12 +146,12 @@ open class RouteController: NSObject, Router { super.init() self.locationManager.delegate = self - resumeNotifications() + self.resumeNotifications() checkForUpdates() checkForLocationUsageDescription() - tunnelIntersectionManager.delegate = self + self.tunnelIntersectionManager.delegate = self } deinit { @@ -168,7 +168,7 @@ open class RouteController: NSObject, Router { } func resumeNotifications() { - NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminate(_:)), name: UIApplication.willTerminateNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(self.applicationWillTerminate(_:)), name: UIApplication.willTerminateNotification, object: nil) } func suspendNotifications() { @@ -176,7 +176,7 @@ open class RouteController: NSObject, Router { } @objc private func applicationWillTerminate(_ notification: NSNotification) { - endNavigation() + self.endNavigation() } /** @@ -185,18 +185,18 @@ open class RouteController: NSObject, Router { Will continue monitoring until `suspendLocationUpdates()` is called. */ @objc public func resume() { - locationManager.delegate = self - locationManager.startUpdatingLocation() - locationManager.startUpdatingHeading() + self.locationManager.delegate = self + self.locationManager.startUpdatingLocation() + self.locationManager.startUpdatingHeading() } /** Stops monitoring the user’s location along the route. */ @objc public func suspendLocationUpdates() { - locationManager.stopUpdatingLocation() - locationManager.stopUpdatingHeading() - locationManager.delegate = nil + self.locationManager.stopUpdatingLocation() + self.locationManager.stopUpdatingHeading() + self.locationManager.delegate = nil NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(interpolateLocation), object: nil) } @@ -204,8 +204,8 @@ open class RouteController: NSObject, Router { Ends the current navigation session. */ @objc public func endNavigation() { - suspendLocationUpdates() - suspendNotifications() + self.suspendLocationUpdates() + self.suspendNotifications() } /** @@ -214,7 +214,7 @@ open class RouteController: NSObject, Router { */ @objc public var location: CLLocation? { // If there is no snapped location, and the rawLocation course is unqualified, use the user's heading as long as it is accurate. - if snappedLocation == nil, + if self.snappedLocation == nil, let heading, let loc = rawLocation, !loc.course.isQualified, @@ -222,7 +222,7 @@ open class RouteController: NSObject, Router { return CLLocation(coordinate: loc.coordinate, altitude: loc.altitude, horizontalAccuracy: loc.horizontalAccuracy, verticalAccuracy: loc.verticalAccuracy, course: heading.trueHeading, speed: loc.speed, timestamp: loc.timestamp) } - return snappedLocation ?? rawLocation + return self.snappedLocation ?? self.rawLocation } /** @@ -230,7 +230,7 @@ open class RouteController: NSObject, Router { - important: If the rawLocation is outside of the route snapping tolerances, this value is nil. */ var snappedLocation: CLLocation? { - rawLocation?.snapped(to: routeProgress.currentLegProgress) + self.rawLocation?.snapped(to: self.routeProgress.currentLegProgress) } var heading: CLHeading? @@ -241,16 +241,16 @@ open class RouteController: NSObject, Router { */ var rawLocation: CLLocation? { didSet { - updateDistanceToManeuver() + self.updateDistanceToManeuver() } } func updateDistanceToManeuver() { guard let coordinates = routeProgress.currentLegProgress.currentStep.coordinates, let coordinate = rawLocation?.coordinate else { - userSnapToStepDistanceFromManeuver = nil + self.userSnapToStepDistanceFromManeuver = nil return } - userSnapToStepDistanceFromManeuver = Polyline(coordinates).distance(from: coordinate) + self.userSnapToStepDistanceFromManeuver = Polyline(coordinates).distance(from: coordinate) } /** @@ -320,21 +320,21 @@ extension RouteController: CLLocationManagerDelegate { speed: location.speed, timestamp: Date()) - locationManager(locationManager, didUpdateLocations: [interpolatedLocation]) + self.locationManager(self.locationManager, didUpdateLocations: [interpolatedLocation]) } @objc public func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { - heading = newHeading + self.heading = newHeading } @objc public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let filteredLocations = locations.filter(\.isQualified) - if !filteredLocations.isEmpty, hasFoundOneQualifiedLocation == false { - hasFoundOneQualifiedLocation = true + if !filteredLocations.isEmpty, self.hasFoundOneQualifiedLocation == false { + self.hasFoundOneQualifiedLocation = true } - let currentStepProgress = routeProgress.currentLegProgress.currentStepProgress + let currentStepProgress = self.routeProgress.currentLegProgress.currentStepProgress var potentialLocation: CLLocation? @@ -342,13 +342,13 @@ extension RouteController: CLLocationManagerDelegate { if let lastFiltered = filteredLocations.last { potentialLocation = lastFiltered // `filteredLocations` does not contain good locations and we have found at least one good location previously. - } else if hasFoundOneQualifiedLocation { + } else if self.hasFoundOneQualifiedLocation { if let lastLocation = locations.last, delegate?.routeController?(self, shouldDiscard: lastLocation) ?? true { // Allow the user puck to advance. A stationary puck is not great. - rawLocation = lastLocation + self.rawLocation = lastLocation // Check for a tunnel intersection at the current step we found the bad location update. - tunnelIntersectionManager.checkForTunnelIntersection(at: lastLocation, routeProgress: routeProgress) + self.tunnelIntersectionManager.checkForTunnelIntersection(at: lastLocation, routeProgress: self.routeProgress) return } @@ -362,19 +362,19 @@ extension RouteController: CLLocationManagerDelegate { return } - rawLocation = location + self.rawLocation = location - delegate?.routeController?(self, didUpdate: [location]) + self.delegate?.routeController?(self, didUpdate: [location]) - NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(interpolateLocation), object: nil) + NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.interpolateLocation), object: nil) - if isDeadReckoningEnabled { - perform(#selector(interpolateLocation), with: nil, afterDelay: 1.1) + if self.isDeadReckoningEnabled { + perform(#selector(self.interpolateLocation), with: nil, afterDelay: 1.1) } let currentStep = currentStepProgress.step - updateIntersectionIndex(for: currentStepProgress) + self.updateIntersectionIndex(for: currentStepProgress) // Notify observers if the step’s remaining distance has changed. let polyline = Polyline(routeProgress.currentLegProgress.currentStep.coordinates!) if let closestCoordinate = polyline.closestCoordinate(to: location.coordinate) { @@ -382,38 +382,38 @@ extension RouteController: CLLocationManagerDelegate { let distanceTraveled = currentStep.distance - remainingDistance currentStepProgress.distanceTraveled = distanceTraveled NotificationCenter.default.post(name: .routeControllerProgressDidChange, object: self, userInfo: [ - RouteControllerNotificationUserInfoKey.routeProgressKey: routeProgress, + RouteControllerNotificationUserInfoKey.routeProgressKey: self.routeProgress, RouteControllerNotificationUserInfoKey.locationKey: self.location!, // guaranteed value RouteControllerNotificationUserInfoKey.rawLocationKey: location // raw ]) // Check for a tunnel intersection whenever the current route step progresses. - tunnelIntersectionManager.checkForTunnelIntersection(at: location, routeProgress: routeProgress) + self.tunnelIntersectionManager.checkForTunnelIntersection(at: location, routeProgress: self.routeProgress) } - updateDistanceToIntersection(from: location) - updateRouteStepProgress(for: location) - updateRouteLegProgress(for: location) - updateVisualInstructionProgress() + self.updateDistanceToIntersection(from: location) + self.updateRouteStepProgress(for: location) + self.updateRouteLegProgress(for: location) + self.updateVisualInstructionProgress() - guard userIsOnRoute(location) || !(delegate?.routeController?(self, shouldRerouteFrom: location) ?? true) else { - rerouteForDiversion(from: location, along: routeProgress) + guard self.userIsOnRoute(location) || !(self.delegate?.routeController?(self, shouldRerouteFrom: location) ?? true) else { + self.rerouteForDiversion(from: location, along: self.routeProgress) return } - updateSpokenInstructionProgress() + self.updateSpokenInstructionProgress() // Check for faster route given users current location - guard reroutesProactively else { return } + guard self.reroutesProactively else { return } // Only check for faster routes or ETA updates if the user has plenty of time left on the route (10+min) // Except when configured in the SDK that we may - guard routeProgress.durationRemaining > 600 || !shouldCheckForRerouteInLastMinutes else { return } + guard self.routeProgress.durationRemaining > 600 || !self.shouldCheckForRerouteInLastMinutes else { return } // If the user is approaching a maneuver (within 70secs of the maneuver), don't check for a faster routes or ETA updates - guard routeProgress.currentLegProgress.currentStepProgress.durationRemaining > RouteControllerMediumAlertInterval else { return } + guard self.routeProgress.currentLegProgress.currentStepProgress.durationRemaining > RouteControllerMediumAlertInterval else { return } - checkForNewRoute(from: location) + self.checkForNewRoute(from: location) } func updateIntersectionIndex(for currentStepProgress: RouteStepProgress) { @@ -423,19 +423,19 @@ extension RouteController: CLLocationManagerDelegate { } func updateRouteLegProgress(for location: CLLocation) { - let currentDestination = routeProgress.currentLeg.destination + let currentDestination = self.routeProgress.currentLeg.destination guard let remainingVoiceInstructions = routeProgress.currentLegProgress.currentStepProgress.remainingSpokenInstructions else { return } - if routeProgress.currentLegProgress.remainingSteps.count <= 1, remainingVoiceInstructions.count == 0, currentDestination != previousArrivalWaypoint { - previousArrivalWaypoint = currentDestination + if self.routeProgress.currentLegProgress.remainingSteps.count <= 1, remainingVoiceInstructions.count == 0, currentDestination != self.previousArrivalWaypoint { + self.previousArrivalWaypoint = currentDestination - routeProgress.currentLegProgress.userHasArrivedAtWaypoint = true + self.routeProgress.currentLegProgress.userHasArrivedAtWaypoint = true - let advancesToNextLeg = delegate?.routeController?(self, didArriveAt: currentDestination) ?? true + let advancesToNextLeg = self.delegate?.routeController?(self, didArriveAt: currentDestination) ?? true - if !routeProgress.isFinalLeg, advancesToNextLeg { - routeProgress.legIndex += 1 - updateDistanceToManeuver() + if !self.routeProgress.isFinalLeg, advancesToNextLeg { + self.routeProgress.legIndex += 1 + self.updateDistanceToManeuver() } } } @@ -444,17 +444,17 @@ extension RouteController: CLLocationManagerDelegate { Monitors the user's course to see if it is consistently moving away from what we expect the course to be at a given point. */ func userCourseIsOnRoute(_ location: CLLocation) -> Bool { - let nearByCoordinates = routeProgress.currentLegProgress.nearbyCoordinates + let nearByCoordinates = self.routeProgress.currentLegProgress.nearbyCoordinates guard let calculatedCourseForLocationOnStep = location.interpolatedCourse(along: nearByCoordinates) else { return true } let maxUpdatesAwayFromRouteGivenAccuracy = Int(location.horizontalAccuracy / Double(RouteControllerIncorrectCourseMultiplier)) - if movementsAwayFromRoute >= max(RouteControllerMinNumberOfInCorrectCourses, maxUpdatesAwayFromRouteGivenAccuracy) { + if self.movementsAwayFromRoute >= max(RouteControllerMinNumberOfInCorrectCourses, maxUpdatesAwayFromRouteGivenAccuracy) { return false } else if location.shouldSnapCourse(toRouteWith: calculatedCourseForLocationOnStep) { - movementsAwayFromRoute = 0 + self.movementsAwayFromRoute = 0 } else { - movementsAwayFromRoute += 1 + self.movementsAwayFromRoute += 1 } return true @@ -467,7 +467,7 @@ extension RouteController: CLLocationManagerDelegate { */ @objc public func userIsOnRoute(_ location: CLLocation) -> Bool { // If the user has arrived, do not continue monitor reroutes, step progress, etc - guard !routeProgress.currentLegProgress.userHasArrivedAtWaypoint && (delegate?.routeController?(self, shouldPreventReroutesWhenArrivingAt: routeProgress.currentLeg.destination) ?? true) else { + guard !self.routeProgress.currentLegProgress.userHasArrivedAtWaypoint && (self.delegate?.routeController?(self, shouldPreventReroutesWhenArrivingAt: self.routeProgress.currentLeg.destination) ?? true) else { return true } @@ -475,10 +475,10 @@ extension RouteController: CLLocationManagerDelegate { let radius = max(reroutingTolerance, RouteControllerManeuverZoneRadius) // This checks all coordinates of the step, if user is close to the step, they on the route - let isCloseToCurrentStep = location.isWithin(radius, of: routeProgress.currentLegProgress.currentStep) + let isCloseToCurrentStep = location.isWithin(radius, of: self.routeProgress.currentLegProgress.currentStep) // If the user is either close to the current step or at least driving in the right direction, we assume the user is on route - guard !isCloseToCurrentStep || !userCourseIsOnRoute(location) else { return true } + guard !isCloseToCurrentStep || !self.userCourseIsOnRoute(location) else { return true } // Check and see if the user is near a future step. guard let nearestStep = routeProgress.currentLegProgress.closestStep(to: location.coordinate) else { @@ -487,8 +487,8 @@ extension RouteController: CLLocationManagerDelegate { if nearestStep.distance < RouteControllerUserLocationSnappingDistance { // Only advance the stepIndex to a future step if the step is new. Otherwise, the user is still on the current step. - if nearestStep.index != routeProgress.currentLegProgress.stepIndex { - advanceStepIndex(to: nearestStep.index) + if nearestStep.index != self.routeProgress.currentLegProgress.stepIndex { + self.advanceStepIndex(to: nearestStep.index) } return true } @@ -497,7 +497,7 @@ extension RouteController: CLLocationManagerDelegate { } func checkForNewRoute(from location: CLLocation) { - guard !isFindingFasterRoute else { + guard !self.isFindingFasterRoute else { return } @@ -511,17 +511,17 @@ extension RouteController: CLLocationManagerDelegate { } // Only check every so often for a faster route. - guard location.timestamp.timeIntervalSince(lastLocationDate) >= routeControllerProactiveReroutingInterval else { + guard location.timestamp.timeIntervalSince(lastLocationDate) >= self.routeControllerProactiveReroutingInterval else { return } - let durationRemaining = routeProgress.durationRemaining + let durationRemaining = self.routeProgress.durationRemaining - isFindingFasterRoute = true + self.isFindingFasterRoute = true print("[RouteController] Checking for faster/updated route...") - getDirections(from: location, along: routeProgress) { [weak self] mostSimilarRoute, routes, _ in + self.getDirections(from: location, along: self.routeProgress) { [weak self] mostSimilarRoute, routes, _ in guard let self else { return } // Every request should reset the lastLocationDate, else we spam the server by calling this method every location update. @@ -529,13 +529,13 @@ extension RouteController: CLLocationManagerDelegate { self.lastLocationDate = nil // Also only do one 'findFasterRoute' call per time - isFindingFasterRoute = false + self.isFindingFasterRoute = false guard let route = mostSimilarRoute, let routes else { return } - applyNewRerouteIfNeeded(mostSimilarRoute: route, allRoutes: routes, currentUpcomingManeuver: currentUpcomingManeuver, durationRemaining: durationRemaining) + self.applyNewRerouteIfNeeded(mostSimilarRoute: route, allRoutes: routes, currentUpcomingManeuver: currentUpcomingManeuver, durationRemaining: durationRemaining) } } @@ -545,7 +545,7 @@ extension RouteController: CLLocationManagerDelegate { } // Current and First step of old and new route should be significant enough of a maneuver before applying a faster route, so we don't apply the route just before a maneuver will occur - let isFirstStepSignificant = firstStep.expectedTravelTime >= RouteControllerMediumAlertInterval && routeProgress.currentLegProgress.currentStepProgress.durationRemaining > RouteControllerMediumAlertInterval + let isFirstStepSignificant = firstStep.expectedTravelTime >= RouteControllerMediumAlertInterval && self.routeProgress.currentLegProgress.currentStepProgress.durationRemaining > RouteControllerMediumAlertInterval // Current maneuver should correspond to the next maneuver in the new route let hasSameUpcomingManeuver = firstLeg.steps.indices.contains(1) ? currentUpcomingManeuver == firstLeg.steps[1] : false @@ -554,7 +554,7 @@ extension RouteController: CLLocationManagerDelegate { let isRouteFaster = mostSimilarRoute.expectedTravelTime <= 0.9 * durationRemaining // Only check for alternatives if the user has plenty of time left on the route (10min+) - let userHasEnoughTimeOnRoute = routeProgress.durationRemaining > 600 + let userHasEnoughTimeOnRoute = self.routeProgress.durationRemaining > 600 print("[RouteController] applyNewRerouteIfNeeded called -> Significant first step: \(isFirstStepSignificant), Same upcoming maneuver: \(hasSameUpcomingManeuver), Route is faster: \(isRouteFaster)") @@ -568,16 +568,16 @@ extension RouteController: CLLocationManagerDelegate { print("[RouteController] Found faster route") // Need to set this for notifications being sent - didFindFasterRoute = true + self.didFindFasterRoute = true // If the upcoming maneuver in the new route is the same as the current upcoming maneuver, don't announce it again, just set new progress - routeProgress = RouteProgress(route: mostSimilarRoute, legIndex: 0, spokenInstructionIndex: routeProgress.currentLegProgress.currentStepProgress.spokenInstructionIndex) + self.routeProgress = RouteProgress(route: mostSimilarRoute, legIndex: 0, spokenInstructionIndex: self.routeProgress.currentLegProgress.currentStepProgress.spokenInstructionIndex) // Let delegate know - delegate?.routeController?(self, didRerouteAlong: mostSimilarRoute, reason: .fasterRoute) + self.delegate?.routeController?(self, didRerouteAlong: mostSimilarRoute, reason: .fasterRoute) // Reset flag for notification - didFindFasterRoute = false + self.didFindFasterRoute = false } // If route is not faster, but matches criteria and we get a match that is similar enough (so we don't apply a route alternative that the user doesn't want), we will apply the route too @@ -589,24 +589,24 @@ extension RouteController: CLLocationManagerDelegate { var routeToApply = matchingRoute.route // When testing flag is flipped, return instead one of the testing routes - if shouldReturnTestingETAUpdateReroutes { + if self.shouldReturnTestingETAUpdateReroutes { let rightOrLeft = Bool.random() - routeToApply = rightOrLeft ? testA12ToVeenendaalNormal : testA12ToVeenendaalNormalWithTraffic + routeToApply = rightOrLeft ? self.testA12ToVeenendaalNormal : self.testA12ToVeenendaalNormalWithTraffic print("[RouteController] Testing route: ON") } - if isExpectedTravelTimeChangedSignificantly || shouldReturnTestingETAUpdateReroutes { + if isExpectedTravelTimeChangedSignificantly || self.shouldReturnTestingETAUpdateReroutes { // Set new route and inform delegates print("[RouteController] Found matching route \(matchingRoute.matchPercentage)%, updating ETA...") - print("[RouteController] Duration remaining CURRENT: \(routeProgress.durationRemaining)") + print("[RouteController] Duration remaining CURRENT: \(self.routeProgress.durationRemaining)") print("[RouteController] Expected travel time: \(matchingRoute.route.expectedTravelTime)") print("[RouteController] Set the new route") // Don't announce new route - routeProgress = RouteProgress(route: routeToApply, legIndex: 0, spokenInstructionIndex: routeProgress.currentLegProgress.currentStepProgress.spokenInstructionIndex) + self.routeProgress = RouteProgress(route: routeToApply, legIndex: 0, spokenInstructionIndex: self.routeProgress.currentLegProgress.currentStepProgress.spokenInstructionIndex) // Inform delegate - delegate?.routeController?(self, didRerouteAlong: routeToApply, reason: .ETAUpdate) + self.delegate?.routeController?(self, didRerouteAlong: routeToApply, reason: .ETAUpdate) } } } @@ -619,20 +619,20 @@ extension RouteController: CLLocationManagerDelegate { } } - if isRerouting { + if self.isRerouting { return } - isRerouting = true + self.isRerouting = true - delegate?.routeController?(self, willRerouteFrom: location) + self.delegate?.routeController?(self, willRerouteFrom: location) NotificationCenter.default.post(name: .routeControllerWillReroute, object: self, userInfo: [ RouteControllerNotificationUserInfoKey.locationKey: location ]) lastRerouteLocation = location - getDirections(from: location, along: progress) { [weak self] route, _, error in + self.getDirections(from: location, along: progress) { [weak self] route, _, error in guard let strongSelf = self else { return } @@ -684,18 +684,18 @@ extension RouteController: CLLocationManagerDelegate { } func getDirections(from location: CLLocation, along progress: RouteProgress, completion: @escaping (_ mostSimilarRoute: Route?, _ routes: [Route]?, _ error: Error?) -> Void) { - if delegate?.routeControllerGetDirections?(from: location, along: progress, completion: completion) != true { + if self.delegate?.routeControllerGetDirections?(from: location, along: progress, completion: completion) != true { // Run the default route calculation if the delegate method is not defined or does not return true - routeTask?.cancel() + self.routeTask?.cancel() let options = progress.reroutingOptions(with: location) - lastRerouteLocation = location + self.lastRerouteLocation = location let complete = { (mostSimilarRoute: Route?, routes: [Route]?, error: NSError?) in completion(mostSimilarRoute, routes, error) } - routeTask = directions.calculate(options) { _, potentialRoutes, potentialError in + self.routeTask = self.directions.calculate(options) { _, potentialRoutes, potentialError in guard let routes = potentialRoutes else { return complete(nil, nil, potentialError) @@ -710,27 +710,27 @@ extension RouteController: CLLocationManagerDelegate { func updateDistanceToIntersection(from location: CLLocation) { guard var intersections = routeProgress.currentLegProgress.currentStepProgress.step.intersections else { return } - let currentStepProgress = routeProgress.currentLegProgress.currentStepProgress + let currentStepProgress = self.routeProgress.currentLegProgress.currentStepProgress // The intersections array does not include the upcoming maneuver intersection. if let upcomingStep = routeProgress.currentLegProgress.upComingStep, let upcomingIntersection = upcomingStep.intersections, let firstUpcomingIntersection = upcomingIntersection.first { intersections += [firstUpcomingIntersection] } - routeProgress.currentLegProgress.currentStepProgress.intersectionsIncludingUpcomingManeuverIntersection = intersections + self.routeProgress.currentLegProgress.currentStepProgress.intersectionsIncludingUpcomingManeuverIntersection = intersections if let upcomingIntersection = routeProgress.currentLegProgress.currentStepProgress.upcomingIntersection { - routeProgress.currentLegProgress.currentStepProgress.userDistanceToUpcomingIntersection = Polyline(currentStepProgress.step.coordinates!).distance(from: location.coordinate, to: upcomingIntersection.location) + self.routeProgress.currentLegProgress.currentStepProgress.userDistanceToUpcomingIntersection = Polyline(currentStepProgress.step.coordinates!).distance(from: location.coordinate, to: upcomingIntersection.location) } - if routeProgress.currentLegProgress.currentStepProgress.intersectionDistances == nil { - routeProgress.currentLegProgress.currentStepProgress.intersectionDistances = [CLLocationDistance]() - updateIntersectionDistances() + if self.routeProgress.currentLegProgress.currentStepProgress.intersectionDistances == nil { + self.routeProgress.currentLegProgress.currentStepProgress.intersectionDistances = [CLLocationDistance]() + self.updateIntersectionDistances() } } func updateRouteStepProgress(for location: CLLocation) { - guard routeProgress.currentLegProgress.remainingSteps.count > 0 else { return } + guard self.routeProgress.currentLegProgress.remainingSteps.count > 0 else { return } guard let userSnapToStepDistanceFromManeuver else { return } var courseMatchesManeuverFinalHeading = false @@ -756,34 +756,34 @@ extension RouteController: CLLocationManagerDelegate { } } - let step = routeProgress.currentLegProgress.upComingStep?.maneuverLocation ?? routeProgress.currentLegProgress.currentStep.maneuverLocation + let step = self.routeProgress.currentLegProgress.upComingStep?.maneuverLocation ?? self.routeProgress.currentLegProgress.currentStep.maneuverLocation let userAbsoluteDistance = step.distance(to: location.coordinate) - let lastKnownUserAbsoluteDistance = routeProgress.currentLegProgress.currentStepProgress.userDistanceToManeuverLocation + let lastKnownUserAbsoluteDistance = self.routeProgress.currentLegProgress.currentStepProgress.userDistanceToManeuverLocation if userSnapToStepDistanceFromManeuver <= RouteControllerManeuverZoneRadius, courseMatchesManeuverFinalHeading || (userAbsoluteDistance > lastKnownUserAbsoluteDistance && lastKnownUserAbsoluteDistance > RouteControllerManeuverZoneRadius) { - advanceStepIndex() + self.advanceStepIndex() } - routeProgress.currentLegProgress.currentStepProgress.userDistanceToManeuverLocation = userAbsoluteDistance + self.routeProgress.currentLegProgress.currentStepProgress.userDistanceToManeuverLocation = userAbsoluteDistance } func updateSpokenInstructionProgress() { guard let userSnapToStepDistanceFromManeuver else { return } guard let spokenInstructions = routeProgress.currentLegProgress.currentStepProgress.remainingSpokenInstructions else { return } - let firstInstructionOnFirstStep = speakFirstInstructionOnFirstStep + let firstInstructionOnFirstStep = self.speakFirstInstructionOnFirstStep // Always give the first voice announcement when beginning a leg. - ? routeProgress.currentLegProgress.stepIndex == 0 && routeProgress.currentLegProgress.currentStepProgress.spokenInstructionIndex == 0 + ? self.routeProgress.currentLegProgress.stepIndex == 0 && self.routeProgress.currentLegProgress.currentStepProgress.spokenInstructionIndex == 0 : false for voiceInstruction in spokenInstructions { if userSnapToStepDistanceFromManeuver <= voiceInstruction.distanceAlongStep || firstInstructionOnFirstStep { NotificationCenter.default.post(name: .routeControllerDidPassSpokenInstructionPoint, object: self, userInfo: [ - RouteControllerNotificationUserInfoKey.routeProgressKey: routeProgress + RouteControllerNotificationUserInfoKey.routeProgressKey: self.routeProgress ]) - routeProgress.currentLegProgress.currentStepProgress.spokenInstructionIndex += 1 + self.routeProgress.currentLegProgress.currentStepProgress.spokenInstructionIndex += 1 return } } @@ -793,15 +793,15 @@ extension RouteController: CLLocationManagerDelegate { guard let userSnapToStepDistanceFromManeuver else { return } guard let visualInstructions = routeProgress.currentLegProgress.currentStepProgress.remainingVisualInstructions else { return } - let firstInstructionOnFirstStep = routeProgress.currentLegProgress.stepIndex == 0 && routeProgress.currentLegProgress.currentStepProgress.visualInstructionIndex == 0 + let firstInstructionOnFirstStep = self.routeProgress.currentLegProgress.stepIndex == 0 && self.routeProgress.currentLegProgress.currentStepProgress.visualInstructionIndex == 0 for visualInstruction in visualInstructions { if userSnapToStepDistanceFromManeuver <= visualInstruction.distanceAlongStep || firstInstructionOnFirstStep { NotificationCenter.default.post(name: .routeControllerDidPassVisualInstructionPoint, object: self, userInfo: [ - RouteControllerNotificationUserInfoKey.routeProgressKey: routeProgress + RouteControllerNotificationUserInfoKey.routeProgressKey: self.routeProgress ]) - routeProgress.currentLegProgress.currentStepProgress.visualInstructionIndex += 1 + self.routeProgress.currentLegProgress.currentStepProgress.visualInstructionIndex += 1 return } } @@ -809,21 +809,21 @@ extension RouteController: CLLocationManagerDelegate { func advanceStepIndex(to: Array.Index? = nil) { if let forcedStepIndex = to { - guard forcedStepIndex < routeProgress.currentLeg.steps.count else { return } - routeProgress.currentLegProgress.stepIndex = forcedStepIndex + guard forcedStepIndex < self.routeProgress.currentLeg.steps.count else { return } + self.routeProgress.currentLegProgress.stepIndex = forcedStepIndex } else { - routeProgress.currentLegProgress.stepIndex += 1 + self.routeProgress.currentLegProgress.stepIndex += 1 } - updateIntersectionDistances() - updateDistanceToManeuver() + self.updateIntersectionDistances() + self.updateDistanceToManeuver() } func updateIntersectionDistances() { if let coordinates = routeProgress.currentLegProgress.currentStep.coordinates, let intersections = routeProgress.currentLegProgress.currentStep.intersections { let polyline = Polyline(coordinates) let distances: [CLLocationDistance] = intersections.map { polyline.distance(from: coordinates.first, to: $0.location) } - routeProgress.currentLegProgress.currentStepProgress.intersectionDistances = distances + self.routeProgress.currentLegProgress.currentStepProgress.intersectionDistances = distances } } @@ -871,10 +871,10 @@ extension RouteController: CLLocationManagerDelegate { extension RouteController: TunnelIntersectionManagerDelegate { public func tunnelIntersectionManager(_ manager: TunnelIntersectionManager, willEnableAnimationAt location: CLLocation) { - tunnelIntersectionManager.enableTunnelAnimation(routeController: self, routeProgress: routeProgress) + self.tunnelIntersectionManager.enableTunnelAnimation(routeController: self, routeProgress: self.routeProgress) } public func tunnelIntersectionManager(_ manager: TunnelIntersectionManager, willDisableAnimationAt location: CLLocation) { - tunnelIntersectionManager.suspendTunnelAnimation(at: location, routeController: self) + self.tunnelIntersectionManager.suspendTunnelAnimation(at: location, routeController: self) } } diff --git a/MapboxCoreNavigation/RouteProgress.swift b/MapboxCoreNavigation/RouteProgress.swift index 79a44c5b..66305811 100644 --- a/MapboxCoreNavigation/RouteProgress.swift +++ b/MapboxCoreNavigation/RouteProgress.swift @@ -22,9 +22,9 @@ open class RouteProgress: NSObject { */ @objc public var legIndex: Int { didSet { - assert(legIndex >= 0 && legIndex < route.legs.endIndex) + assert(self.legIndex >= 0 && self.legIndex < self.route.legs.endIndex) // TODO: Set stepIndex to 0 or last index based on whether leg index was incremented or decremented. - currentLegProgress = RouteLegProgress(leg: currentLeg) + self.currentLegProgress = RouteLegProgress(leg: self.currentLeg) } } @@ -32,7 +32,7 @@ open class RouteProgress: NSObject { If waypoints are provided in the `Route`, this will contain which leg the user is on. */ @objc public var currentLeg: RouteLeg { - route.legs[legIndex] + self.route.legs[self.legIndex] } /** @@ -40,42 +40,42 @@ open class RouteProgress: NSObject { */ public var isFinalLeg: Bool { guard let lastLeg = route.legs.last else { return false } - return currentLeg == lastLeg + return self.currentLeg == lastLeg } /** Total distance traveled by user along all legs. */ @objc public var distanceTraveled: CLLocationDistance { - route.legs.prefix(upTo: legIndex).map(\.distance).reduce(0, +) + currentLegProgress.distanceTraveled + self.route.legs.prefix(upTo: self.legIndex).map(\.distance).reduce(0, +) + self.currentLegProgress.distanceTraveled } /** Total seconds remaining on all legs. */ @objc public var durationRemaining: TimeInterval { - route.legs.suffix(from: legIndex + 1).map(\.expectedTravelTime).reduce(0, +) + currentLegProgress.durationRemaining + self.route.legs.suffix(from: self.legIndex + 1).map(\.expectedTravelTime).reduce(0, +) + self.currentLegProgress.durationRemaining } /** Number between 0 and 1 representing how far along the `Route` the user has traveled. */ @objc public var fractionTraveled: Double { - distanceTraveled / route.distance + self.distanceTraveled / self.route.distance } /** Total distance remaining in meters along route. */ @objc public var distanceRemaining: CLLocationDistance { - route.distance - distanceTraveled + self.route.distance - self.distanceTraveled } /** Number of waypoints remaining on the current route. */ @objc public var remainingWaypoints: [Waypoint] { - route.legs.suffix(from: legIndex).map(\.destination) + self.route.legs.suffix(from: self.legIndex).map(\.destination) } /** @@ -107,13 +107,13 @@ open class RouteProgress: NSObject { @objc public init(route: Route, legIndex: Int = 0, spokenInstructionIndex: Int = 0) { self.route = route self.legIndex = legIndex - currentLegProgress = RouteLegProgress(leg: route.legs[legIndex], stepIndex: 0, spokenInstructionIndex: spokenInstructionIndex) + self.currentLegProgress = RouteLegProgress(leg: route.legs[legIndex], stepIndex: 0, spokenInstructionIndex: spokenInstructionIndex) super.init() for (legIndex, leg) in route.legs.enumerated() { var maneuverCoordinateIndex = 0 - congestionTimesPerStep.append([]) + self.congestionTimesPerStep.append([]) /// An index into the route’s coordinates and congestionTravelTimesSegmentsByStep that corresponds to a step’s maneuver location. var congestionTravelTimesSegmentsByLeg: [[TimedCongestionLevel]] = [] @@ -138,27 +138,27 @@ open class RouteProgress: NSObject { stepCongestionValues[segmentCongestion] = (stepCongestionValues[segmentCongestion] ?? 0) + segmentTime } - congestionTimesPerStep[legIndex].append(stepCongestionValues) + self.congestionTimesPerStep[legIndex].append(stepCongestionValues) } } - congestionTravelTimesSegmentsByStep.append(congestionTravelTimesSegmentsByLeg) + self.congestionTravelTimesSegmentsByStep.append(congestionTravelTimesSegmentsByLeg) } } public var averageCongestionLevelRemainingOnLeg: CongestionLevel? { - let coordinatesLeftOnStepCount = Int(floor(Double(currentLegProgress.currentStepProgress.step.coordinateCount) * currentLegProgress.currentStepProgress.fractionTraveled)) + let coordinatesLeftOnStepCount = Int(floor(Double(currentLegProgress.currentStepProgress.step.coordinateCount) * self.currentLegProgress.currentStepProgress.fractionTraveled)) guard coordinatesLeftOnStepCount >= 0 else { return .unknown } - guard legIndex < congestionTravelTimesSegmentsByStep.count, - currentLegProgress.stepIndex < congestionTravelTimesSegmentsByStep[legIndex].count else { return .unknown } + guard self.legIndex < self.congestionTravelTimesSegmentsByStep.count, + self.currentLegProgress.stepIndex < self.congestionTravelTimesSegmentsByStep[self.legIndex].count else { return .unknown } - let congestionTimesForStep = congestionTravelTimesSegmentsByStep[legIndex][currentLegProgress.stepIndex] + let congestionTimesForStep = self.congestionTravelTimesSegmentsByStep[self.legIndex][self.currentLegProgress.stepIndex] guard coordinatesLeftOnStepCount <= congestionTimesForStep.count else { return .unknown } let remainingCongestionTimesForStep = congestionTimesForStep.suffix(from: coordinatesLeftOnStepCount) - let remainingCongestionTimesForRoute = congestionTimesPerStep[legIndex].suffix(from: currentLegProgress.stepIndex + 1) + let remainingCongestionTimesForRoute = self.congestionTimesPerStep[self.legIndex].suffix(from: self.currentLegProgress.stepIndex + 1) var remainingStepCongestionTotals: [CongestionLevel: TimeInterval] = [:] for stepValues in remainingCongestionTimesForRoute { @@ -171,7 +171,7 @@ open class RouteProgress: NSObject { remainingStepCongestionTotals[segmentCongestion] = (remainingStepCongestionTotals[segmentCongestion] ?? 0) + segmentTime } - if durationRemaining < 60 { + if self.durationRemaining < 60 { return .unknown } else { if let max = remainingStepCongestionTotals.max(by: { a, b in a.value < b.value }) { @@ -183,14 +183,14 @@ open class RouteProgress: NSObject { } func reroutingOptions(with current: CLLocation) -> RouteOptions { - let oldOptions = route.routeOptions + let oldOptions = self.route.routeOptions let user = Waypoint(coordinate: current.coordinate) if current.course >= 0 { user.heading = current.course user.headingAccuracy = RouteProgress.reroutingAccuracy } - let newWaypoints = [user] + remainingWaypoints + let newWaypoints = [user] + self.remainingWaypoints let newOptions = oldOptions.copy() as! RouteOptions newOptions.waypoints = newWaypoints @@ -213,8 +213,8 @@ open class RouteLegProgress: NSObject { */ @objc public var stepIndex: Int { didSet { - assert(stepIndex >= 0 && stepIndex < leg.steps.endIndex) - currentStepProgress = RouteStepProgress(step: currentStep) + assert(self.stepIndex >= 0 && self.stepIndex < self.leg.steps.endIndex) + self.currentStepProgress = RouteStepProgress(step: self.currentStep) } } @@ -222,35 +222,35 @@ open class RouteLegProgress: NSObject { The remaining steps for user to complete. */ @objc public var remainingSteps: [RouteStep] { - Array(leg.steps.suffix(from: stepIndex + 1)) + Array(self.leg.steps.suffix(from: self.stepIndex + 1)) } /** Total distance traveled in meters along current leg. */ @objc public var distanceTraveled: CLLocationDistance { - leg.steps.prefix(upTo: stepIndex).map(\.distance).reduce(0, +) + currentStepProgress.distanceTraveled + self.leg.steps.prefix(upTo: self.stepIndex).map(\.distance).reduce(0, +) + self.currentStepProgress.distanceTraveled } /** Duration remaining in seconds on current leg. */ @objc public var durationRemaining: TimeInterval { - remainingSteps.map(\.expectedTravelTime).reduce(0, +) + currentStepProgress.durationRemaining + self.remainingSteps.map(\.expectedTravelTime).reduce(0, +) + self.currentStepProgress.durationRemaining } /** Distance remaining on the current leg. */ @objc public var distanceRemaining: CLLocationDistance { - remainingSteps.map(\.distance).reduce(0, +) + currentStepProgress.distanceRemaining + self.remainingSteps.map(\.distance).reduce(0, +) + self.currentStepProgress.distanceRemaining } /** Number between 0 and 1 representing how far along the current leg the user has traveled. */ @objc public var fractionTraveled: Double { - distanceTraveled / leg.distance + self.distanceTraveled / self.leg.distance } @objc public var userHasArrivedAtWaypoint = false @@ -263,7 +263,7 @@ open class RouteLegProgress: NSObject { return nil } if index > 0 { - return leg.steps[index - 1] + return self.leg.steps[index - 1] } return nil } @@ -275,8 +275,8 @@ open class RouteLegProgress: NSObject { guard let index = leg.steps.firstIndex(of: step) else { return nil } - if index + 1 < leg.steps.endIndex { - return leg.steps[index + 1] + if index + 1 < self.leg.steps.endIndex { + return self.leg.steps[index + 1] } return nil } @@ -287,17 +287,17 @@ open class RouteLegProgress: NSObject { If there is no `priorStep`, nil is returned. */ @objc public var priorStep: RouteStep? { - guard stepIndex - 1 >= 0 else { + guard self.stepIndex - 1 >= 0 else { return nil } - return leg.steps[stepIndex - 1] + return self.leg.steps[self.stepIndex - 1] } /** Returns the current `RouteStep` for the leg the user is on. */ @objc public var currentStep: RouteStep { - leg.steps[stepIndex] + self.leg.steps[self.stepIndex] } /** @@ -306,10 +306,10 @@ open class RouteLegProgress: NSObject { If there is no `upcomingStep`, nil is returned. */ @objc public var upComingStep: RouteStep? { - guard stepIndex + 1 < leg.steps.endIndex else { + guard self.stepIndex + 1 < self.leg.steps.endIndex else { return nil } - return leg.steps[stepIndex + 1] + return self.leg.steps[self.stepIndex + 1] } /** @@ -318,17 +318,17 @@ open class RouteLegProgress: NSObject { If there is no `followOnStep`, nil is returned. */ @objc public var followOnStep: RouteStep? { - guard stepIndex + 2 < leg.steps.endIndex else { + guard self.stepIndex + 2 < self.leg.steps.endIndex else { return nil } - return leg.steps[stepIndex + 2] + return self.leg.steps[self.stepIndex + 2] } /** Return bool whether step provided is the current `RouteStep` the user is on. */ @objc public func isCurrentStep(_ step: RouteStep) -> Bool { - step == currentStep + step == self.currentStep } /** @@ -345,16 +345,16 @@ open class RouteLegProgress: NSObject { @objc public init(leg: RouteLeg, stepIndex: Int = 0, spokenInstructionIndex: Int = 0) { self.leg = leg self.stepIndex = stepIndex - currentStepProgress = RouteStepProgress(step: leg.steps[stepIndex], spokenInstructionIndex: spokenInstructionIndex) + self.currentStepProgress = RouteStepProgress(step: leg.steps[stepIndex], spokenInstructionIndex: spokenInstructionIndex) } /** Returns an array of `CLLocationCoordinate2D` of the prior, current and upcoming step geometry. */ @objc public var nearbyCoordinates: [CLLocationCoordinate2D] { - let priorCoords = priorStep?.coordinates ?? [] - let upcomingCoords = upComingStep?.coordinates ?? [] - let currentCoords = currentStep.coordinates ?? [] + let priorCoords = self.priorStep?.coordinates ?? [] + let upcomingCoords = self.upComingStep?.coordinates ?? [] + let currentCoords = self.currentStep.coordinates ?? [] let nearby = priorCoords + currentCoords + upcomingCoords assert(!nearby.isEmpty, "Step must have coordinates") return nearby @@ -364,12 +364,12 @@ open class RouteLegProgress: NSObject { func closestStep(to coordinate: CLLocationCoordinate2D) -> StepIndexDistance? { var currentClosest: StepIndexDistance? - let remainingSteps = leg.steps.suffix(from: stepIndex) + let remainingSteps = self.leg.steps.suffix(from: self.stepIndex) for (currentStepIndex, step) in remainingSteps.enumerated() { guard let coords = step.coordinates else { continue } guard let closestCoordOnStep = Polyline(coords).closestCoordinate(to: coordinate) else { continue } - let foundIndex = currentStepIndex + stepIndex + let foundIndex = currentStepIndex + self.stepIndex // First time around, currentClosest will be `nil`. guard let currentClosestDistance = currentClosest?.distance else { @@ -410,22 +410,22 @@ open class RouteStepProgress: NSObject { Total distance in meters remaining on current step. */ @objc public var distanceRemaining: CLLocationDistance { - step.distance - distanceTraveled + self.step.distance - self.distanceTraveled } /** Number between 0 and 1 representing fraction of current step traveled. */ @objc public var fractionTraveled: Double { - guard step.distance > 0 else { return 1 } - return distanceTraveled / step.distance + guard self.step.distance > 0 else { return 1 } + return self.distanceTraveled / self.step.distance } /** Number of seconds remaining on current step. */ @objc public var durationRemaining: TimeInterval { - (1 - fractionTraveled) * step.expectedTravelTime + (1 - self.fractionTraveled) * self.step.expectedTravelTime } /** @@ -435,7 +435,7 @@ open class RouteStepProgress: NSObject { */ @objc public init(step: RouteStep, spokenInstructionIndex: Int = 0) { self.step = step - intersectionIndex = 0 + self.intersectionIndex = 0 self.spokenInstructionIndex = spokenInstructionIndex } @@ -456,7 +456,7 @@ open class RouteStepProgress: NSObject { return nil } - return intersections[intersections.index(after: intersectionIndex)] + return intersections[intersections.index(after: self.intersectionIndex)] } /** @@ -474,7 +474,7 @@ open class RouteStepProgress: NSObject { return nil } - return intersections[intersectionIndex] + return intersections[self.intersectionIndex] } /** @@ -497,7 +497,7 @@ open class RouteStepProgress: NSObject { */ @objc public var remainingVisualInstructions: [VisualInstructionBanner]? { guard let visualInstructions = step.instructionsDisplayedAlongStep else { return nil } - return Array(visualInstructions.suffix(from: visualInstructionIndex)) + return Array(visualInstructions.suffix(from: self.visualInstructionIndex)) } /** @@ -513,7 +513,7 @@ open class RouteStepProgress: NSObject { let instructions = step.instructionsSpokenAlongStep, spokenInstructionIndex <= instructions.endIndex else { return nil } - return Array(instructions.suffix(from: spokenInstructionIndex)) + return Array(instructions.suffix(from: self.spokenInstructionIndex)) } /** @@ -521,8 +521,8 @@ open class RouteStepProgress: NSObject { */ @objc public var currentSpokenInstruction: SpokenInstruction? { guard let instructionsSpokenAlongStep = step.instructionsSpokenAlongStep else { return nil } - guard spokenInstructionIndex < instructionsSpokenAlongStep.count else { return nil } - return instructionsSpokenAlongStep[spokenInstructionIndex] + guard self.spokenInstructionIndex < instructionsSpokenAlongStep.count else { return nil } + return instructionsSpokenAlongStep[self.spokenInstructionIndex] } /** @@ -530,7 +530,7 @@ open class RouteStepProgress: NSObject { */ @objc public var currentVisualInstruction: VisualInstructionBanner? { guard let instructionsDisplayedAlongStep = step.instructionsDisplayedAlongStep else { return nil } - guard visualInstructionIndex < instructionsDisplayedAlongStep.count else { return nil } - return instructionsDisplayedAlongStep[visualInstructionIndex] + guard self.visualInstructionIndex < instructionsDisplayedAlongStep.count else { return nil } + return instructionsDisplayedAlongStep[self.visualInstructionIndex] } } diff --git a/MapboxCoreNavigation/RouteStep.swift b/MapboxCoreNavigation/RouteStep.swift index 6fa1edb2..5c64e591 100644 --- a/MapboxCoreNavigation/RouteStep.swift +++ b/MapboxCoreNavigation/RouteStep.swift @@ -24,7 +24,7 @@ extension RouteStep { Returns true if the route travels on a motorway primarily identified by a route number rather than a road name. */ var isNumberedMotorway: Bool { - guard isMotorway else { return false } + guard self.isMotorway else { return false } guard let codes, let digitRange = codes.first?.rangeOfCharacter(from: .decimalDigits) else { return false } diff --git a/MapboxCoreNavigation/SessionState.swift b/MapboxCoreNavigation/SessionState.swift index f4cc409d..6d4a85a7 100644 --- a/MapboxCoreNavigation/SessionState.swift +++ b/MapboxCoreNavigation/SessionState.swift @@ -39,22 +39,22 @@ struct SessionState { public mutating func reportChange(to orientation: UIDeviceOrientation) { if orientation.isPortrait { - timeSpentInLandscape += abs(lastTimeInPortrait.timeIntervalSinceNow) - lastTimeInPortrait = Date() + self.timeSpentInLandscape += abs(self.lastTimeInPortrait.timeIntervalSinceNow) + self.lastTimeInPortrait = Date() } else if orientation.isLandscape { - timeSpentInPortrait += abs(lastTimeInLandscape.timeIntervalSinceNow) - lastTimeInLandscape = Date() + self.timeSpentInPortrait += abs(self.lastTimeInLandscape.timeIntervalSinceNow) + self.lastTimeInLandscape = Date() } } public mutating func reportChange(to applicationState: UIApplication.State) { if applicationState == .active { - timeSpentInForeground += abs(lastTimeInBackground.timeIntervalSinceNow) + self.timeSpentInForeground += abs(self.lastTimeInBackground.timeIntervalSinceNow) - lastTimeInForeground = Date() + self.lastTimeInForeground = Date() } else if applicationState == .background { - timeSpentInBackground += abs(lastTimeInForeground.timeIntervalSinceNow) - lastTimeInBackground = Date() + self.timeSpentInBackground += abs(self.lastTimeInForeground.timeIntervalSinceNow) + self.lastTimeInBackground = Date() } } } @@ -68,13 +68,13 @@ class FixedLengthQueue { } public func push(_ obj: T) { - objects.append(obj) - if objects.count == length { - objects.remove(at: 0) + self.objects.append(obj) + if self.objects.count == self.length { + self.objects.remove(at: 0) } } public var allObjects: [T] { - Array(objects) + Array(self.objects) } } diff --git a/MapboxCoreNavigation/SimulatedLocationManager.swift b/MapboxCoreNavigation/SimulatedLocationManager.swift index abbab58d..1b6ef42b 100644 --- a/MapboxCoreNavigation/SimulatedLocationManager.swift +++ b/MapboxCoreNavigation/SimulatedLocationManager.swift @@ -18,7 +18,7 @@ private class SimulatedLocation: CLLocation { var turnPenalty: Double = 0 override var description: String { - "\(super.description) \(turnPenalty)" + "\(super.description) \(self.turnPenalty)" } } @@ -42,23 +42,23 @@ open class SimulatedLocationManager: NavigationLocationManager { @objc public var speedMultiplier: Double = 1 @objc override open var location: CLLocation? { - currentLocation + self.currentLocation } var route: Route? { didSet { - reset() + self.reset() } } override public func copy(with zone: NSZone? = nil) -> Any { let copy = SimulatedLocationManager(route: route!) - copy.currentDistance = currentDistance - copy.currentLocation = currentLocation - copy.currentSpeed = currentSpeed - copy.locations = locations - copy.routeLine = routeLine - copy.speedMultiplier = speedMultiplier + copy.currentDistance = self.currentDistance + copy.currentLocation = self.currentLocation + copy.currentSpeed = self.currentSpeed + copy.locations = self.locations + copy.routeLine = self.routeLine + copy.speedMultiplier = self.speedMultiplier return copy } @@ -72,7 +72,7 @@ open class SimulatedLocationManager: NavigationLocationManager { */ @objc public init(route: Route) { super.init() - initializeSimulatedLocationManager(for: route, currentDistance: 0, currentSpeed: 30) + self.initializeSimulatedLocationManager(for: route, currentDistance: 0, currentSpeed: 30) } /** @@ -83,8 +83,8 @@ open class SimulatedLocationManager: NavigationLocationManager { */ @objc public init(routeProgress: RouteProgress) { super.init() - let currentDistance = calculateCurrentDistance(routeProgress.distanceTraveled) - initializeSimulatedLocationManager(for: routeProgress.route, currentDistance: currentDistance, currentSpeed: 0) + let currentDistance = self.calculateCurrentDistance(routeProgress.distanceTraveled) + self.initializeSimulatedLocationManager(for: routeProgress.route, currentDistance: currentDistance, currentSpeed: 0) } private func initializeSimulatedLocationManager(for route: Route, currentDistance: CLLocationDistance, currentSpeed: CLLocationSpeed) { @@ -92,23 +92,23 @@ open class SimulatedLocationManager: NavigationLocationManager { self.currentDistance = currentDistance self.route = route - NotificationCenter.default.addObserver(self, selector: #selector(didReroute(_:)), name: .routeControllerDidReroute, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(progressDidChange(_:)), name: .routeControllerProgressDidChange, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(self.didReroute(_:)), name: .routeControllerDidReroute, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(self.progressDidChange(_:)), name: .routeControllerProgressDidChange, object: nil) } private func reset() { if let coordinates = route?.coordinates { - routeLine = coordinates - locations = coordinates.simulatedLocationsWithTurnPenalties() + self.routeLine = coordinates + self.locations = coordinates.simulatedLocationsWithTurnPenalties() } } private func calculateCurrentDistance(_ distance: CLLocationDistance) -> CLLocationDistance { - distance + (currentSpeed * speedMultiplier) + distance + (self.currentSpeed * self.speedMultiplier) } @objc private func progressDidChange(_ notification: Notification) { - routeProgress = notification.userInfo![RouteControllerNotificationUserInfoKey.routeProgressKey] as? RouteProgress + self.routeProgress = notification.userInfo![RouteControllerNotificationUserInfoKey.routeProgressKey] as? RouteProgress } @objc private func didReroute(_ notification: Notification) { @@ -116,7 +116,7 @@ open class SimulatedLocationManager: NavigationLocationManager { return } - route = routeController.routeProgress.route + self.route = routeController.routeProgress.route } deinit { @@ -125,7 +125,7 @@ open class SimulatedLocationManager: NavigationLocationManager { } override open func startUpdatingLocation() { - DispatchQueue.main.async(execute: tick) + DispatchQueue.main.async(execute: self.tick) } override open func stopUpdatingLocation() { @@ -135,7 +135,7 @@ open class SimulatedLocationManager: NavigationLocationManager { } @objc fileprivate func tick() { - NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(tick), object: nil) + NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.tick), object: nil) let polyline = Polyline(routeLine) @@ -147,7 +147,7 @@ open class SimulatedLocationManager: NavigationLocationManager { guard let lookAheadCoordinate = polyline.coordinateFromStart(distance: currentDistance + 10) else { return } guard let closestCoordinate = polyline.closestCoordinate(to: newCoordinate) else { return } - let closestLocation = locations[closestCoordinate.index] + let closestLocation = self.locations[closestCoordinate.index] let distanceToClosest = closestLocation.distance(from: CLLocation(newCoordinate)) let distance = min(max(distanceToClosest, 10), safeDistance) @@ -160,9 +160,9 @@ open class SimulatedLocationManager: NavigationLocationManager { let nextCoordinateOnRoute = coordinates.after(element: coordinates[closestCoordinateOnRoute.index]), let time = expectedSegmentTravelTimes.optional[closestCoordinateOnRoute.index] { let distance = coordinates[closestCoordinateOnRoute.index].distance(to: nextCoordinateOnRoute) - currentSpeed = max(distance / time, 2) + self.currentSpeed = max(distance / time, 2) } else { - currentSpeed = calculateCurrentSpeed(distance: distance, coordinatesNearby: coordinatesNearby, closestLocation: closestLocation) + self.currentSpeed = self.calculateCurrentSpeed(distance: distance, coordinatesNearby: coordinatesNearby, closestLocation: closestLocation) } let location = CLLocation(coordinate: newCoordinate, @@ -170,14 +170,14 @@ open class SimulatedLocationManager: NavigationLocationManager { horizontalAccuracy: horizontalAccuracy, verticalAccuracy: verticalAccuracy, course: newCoordinate.direction(to: lookAheadCoordinate).wrap(min: 0, max: 360), - speed: currentSpeed, + speed: self.currentSpeed, timestamp: Date()) - currentLocation = location + self.currentLocation = location lastKnownLocation = location - delegate?.locationManager?(self, didUpdateLocations: [currentLocation]) - currentDistance = calculateCurrentDistance(currentDistance) - perform(#selector(tick), with: nil, afterDelay: 1) + delegate?.locationManager?(self, didUpdateLocations: [self.currentLocation]) + self.currentDistance = self.calculateCurrentDistance(self.currentDistance) + perform(#selector(self.tick), with: nil, afterDelay: 1) } private func calculateCurrentSpeed(distance: CLLocationDistance, coordinatesNearby: [CLLocationCoordinate2D]? = nil, closestLocation: SimulatedLocation) -> CLLocationSpeed { @@ -213,7 +213,7 @@ private extension Array where Element: Hashable { struct OptionalSubscript { var elements: [Element] subscript(index: Int) -> Element? { - index < elements.count ? elements[index] : nil + index < self.elements.count ? self.elements[index] : nil } } diff --git a/MapboxCoreNavigation/String.swift b/MapboxCoreNavigation/String.swift index 2712b50a..324c5d9b 100644 --- a/MapboxCoreNavigation/String.swift +++ b/MapboxCoreNavigation/String.swift @@ -23,7 +23,7 @@ extension String { } var addingXMLEscapes: String { - byReplacing([ + self.byReplacing([ ("&", "&"), ("<", "<"), ("\"", """), @@ -32,15 +32,15 @@ extension String { } var asSSMLAddress: String { - "\(addingXMLEscapes)" + "\(self.addingXMLEscapes)" } var asSSMLCharacters: String { - "\(addingXMLEscapes)" + "\(self.addingXMLEscapes)" } func withSSMLPhoneme(ipaNotation: String) -> String { - "\(addingXMLEscapes)" + "\(self.addingXMLEscapes)" } var isUppercased: Bool { diff --git a/MapboxCoreNavigation/TunnelIntersectionManager.swift b/MapboxCoreNavigation/TunnelIntersectionManager.swift index c54f9a00..bede3f3d 100644 --- a/MapboxCoreNavigation/TunnelIntersectionManager.swift +++ b/MapboxCoreNavigation/TunnelIntersectionManager.swift @@ -53,14 +53,14 @@ open class TunnelIntersectionManager: NSObject { @objc public var tunnelSimulationEnabled: Bool = true func checkForTunnelIntersection(at location: CLLocation, routeProgress: RouteProgress) { - guard tunnelSimulationEnabled else { return } + guard self.tunnelSimulationEnabled else { return } - let tunnelDetected = userWithinTunnelEntranceRadius(at: location, routeProgress: routeProgress) + let tunnelDetected = self.userWithinTunnelEntranceRadius(at: location, routeProgress: routeProgress) if tunnelDetected { - delegate?.tunnelIntersectionManager?(self, willEnableAnimationAt: location) - } else if isAnimationEnabled { - delegate?.tunnelIntersectionManager?(self, willDisableAnimationAt: location) + self.delegate?.tunnelIntersectionManager?(self, willEnableAnimationAt: location) + } else if self.isAnimationEnabled { + self.delegate?.tunnelIntersectionManager?(self, willDisableAnimationAt: location) } } @@ -96,34 +96,34 @@ open class TunnelIntersectionManager: NSObject { } @objc public func enableTunnelAnimation(routeController: RouteController, routeProgress: RouteProgress) { - guard !isAnimationEnabled else { return } + guard !self.isAnimationEnabled else { return } - animatedLocationManager = SimulatedLocationManager(routeProgress: routeProgress) - animatedLocationManager?.delegate = routeController - animatedLocationManager?.routeProgress = routeProgress - animatedLocationManager?.startUpdatingLocation() - animatedLocationManager?.startUpdatingHeading() + self.animatedLocationManager = SimulatedLocationManager(routeProgress: routeProgress) + self.animatedLocationManager?.delegate = routeController + self.animatedLocationManager?.routeProgress = routeProgress + self.animatedLocationManager?.startUpdatingLocation() + self.animatedLocationManager?.startUpdatingHeading() - isAnimationEnabled = true + self.isAnimationEnabled = true } @objc public func suspendTunnelAnimation(at location: CLLocation, routeController: RouteController) { - guard isAnimationEnabled else { return } + guard self.isAnimationEnabled else { return } // Disable the tunnel animation after at least 3 good location updates. if location.isQualified { - tunnelExitLocations.append(location) + self.tunnelExitLocations.append(location) } - guard tunnelExitLocations.count >= 3 else { + guard self.tunnelExitLocations.count >= 3 else { return } - isAnimationEnabled = false + self.isAnimationEnabled = false - animatedLocationManager?.stopUpdatingLocation() - animatedLocationManager?.stopUpdatingHeading() - animatedLocationManager = nil - tunnelExitLocations.removeAll() + self.animatedLocationManager?.stopUpdatingLocation() + self.animatedLocationManager?.stopUpdatingHeading() + self.animatedLocationManager = nil + self.tunnelExitLocations.removeAll() routeController.rawLocation = location } diff --git a/MapboxCoreNavigationTests/DistanceFormatterTests.swift b/MapboxCoreNavigationTests/DistanceFormatterTests.swift index 2663ccad..6b3fe6b4 100644 --- a/MapboxCoreNavigationTests/DistanceFormatterTests.swift +++ b/MapboxCoreNavigationTests/DistanceFormatterTests.swift @@ -14,10 +14,10 @@ class DistanceFormatterTests: XCTestCase { } func assertDistance(_ distance: CLLocationDistance, displayed: String, quantity: String) { - let displayedString = distanceFormatter.string(from: distance) + let displayedString = self.distanceFormatter.string(from: distance) XCTAssertEqual(displayedString, displayed, "Displayed: '\(displayedString)' should be equal to \(displayed)") - let attributedString = distanceFormatter.attributedString(for: distance as NSNumber) + let attributedString = self.distanceFormatter.attributedString(for: distance as NSNumber) XCTAssertEqual(attributedString?.string, displayed, "Displayed: '\(attributedString?.string ?? "")' should be equal to \(displayed)") guard let checkedAttributedString = attributedString else { return @@ -43,84 +43,84 @@ class DistanceFormatterTests: XCTestCase { func testDistanceFormatters_US() { NavigationSettings.shared.distanceUnit = .mile - distanceFormatter.numberFormatter.locale = Locale(identifier: "en-US") + self.distanceFormatter.numberFormatter.locale = Locale(identifier: "en-US") - assertDistance(0, displayed: "0 ft", quantity: "0") - assertDistance(oneFeet * 50, displayed: "50 ft", quantity: "50") - assertDistance(oneFeet * 100, displayed: "100 ft", quantity: "100") - assertDistance(oneFeet * 249, displayed: "250 ft", quantity: "250") - assertDistance(oneFeet * 305, displayed: "300 ft", quantity: "300") - assertDistance(oneMile * 0.1, displayed: "0.1 mi", quantity: "0.1") - assertDistance(oneMile * 0.24, displayed: "0.2 mi", quantity: "0.2") - assertDistance(oneMile * 0.251, displayed: "0.3 mi", quantity: "0.3") - assertDistance(oneMile * 0.75, displayed: "0.8 mi", quantity: "0.8") - assertDistance(oneMile, displayed: "1 mi", quantity: "1") - assertDistance(oneMile * 2.5, displayed: "2.5 mi", quantity: "2.5") - assertDistance(oneMile * 2.9, displayed: "2.9 mi", quantity: "2.9") - assertDistance(oneMile * 3, displayed: "3 mi", quantity: "3") - assertDistance(oneMile * 5.4, displayed: "5 mi", quantity: "5") + self.assertDistance(0, displayed: "0 ft", quantity: "0") + self.assertDistance(oneFeet * 50, displayed: "50 ft", quantity: "50") + self.assertDistance(oneFeet * 100, displayed: "100 ft", quantity: "100") + self.assertDistance(oneFeet * 249, displayed: "250 ft", quantity: "250") + self.assertDistance(oneFeet * 305, displayed: "300 ft", quantity: "300") + self.assertDistance(oneMile * 0.1, displayed: "0.1 mi", quantity: "0.1") + self.assertDistance(oneMile * 0.24, displayed: "0.2 mi", quantity: "0.2") + self.assertDistance(oneMile * 0.251, displayed: "0.3 mi", quantity: "0.3") + self.assertDistance(oneMile * 0.75, displayed: "0.8 mi", quantity: "0.8") + self.assertDistance(oneMile, displayed: "1 mi", quantity: "1") + self.assertDistance(oneMile * 2.5, displayed: "2.5 mi", quantity: "2.5") + self.assertDistance(oneMile * 2.9, displayed: "2.9 mi", quantity: "2.9") + self.assertDistance(oneMile * 3, displayed: "3 mi", quantity: "3") + self.assertDistance(oneMile * 5.4, displayed: "5 mi", quantity: "5") } func testDistanceFormatters_DE() { NavigationSettings.shared.distanceUnit = .kilometer - distanceFormatter.numberFormatter.locale = Locale(identifier: "de-DE") + self.distanceFormatter.numberFormatter.locale = Locale(identifier: "de-DE") - assertDistance(0, displayed: "0 m", quantity: "0") - assertDistance(4, displayed: "5 m", quantity: "5") - assertDistance(11, displayed: "10 m", quantity: "10") - assertDistance(15, displayed: "15 m", quantity: "15") - assertDistance(24, displayed: "25 m", quantity: "25") - assertDistance(89, displayed: "100 m", quantity: "100") - assertDistance(226, displayed: "250 m", quantity: "250") - assertDistance(275, displayed: "300 m", quantity: "300") - assertDistance(500, displayed: "500 m", quantity: "500") - assertDistance(949, displayed: "950 m", quantity: "950") - assertDistance(951, displayed: "950 m", quantity: "950") - assertDistance(999, displayed: "1 km", quantity: "1") - assertDistance(1000, displayed: "1 km", quantity: "1") - assertDistance(1001, displayed: "1 km", quantity: "1") - assertDistance(2500, displayed: "2.5 km", quantity: "2.5") - assertDistance(2900, displayed: "2.9 km", quantity: "2.9") - assertDistance(3000, displayed: "3 km", quantity: "3") - assertDistance(3500, displayed: "4 km", quantity: "4") + self.assertDistance(0, displayed: "0 m", quantity: "0") + self.assertDistance(4, displayed: "5 m", quantity: "5") + self.assertDistance(11, displayed: "10 m", quantity: "10") + self.assertDistance(15, displayed: "15 m", quantity: "15") + self.assertDistance(24, displayed: "25 m", quantity: "25") + self.assertDistance(89, displayed: "100 m", quantity: "100") + self.assertDistance(226, displayed: "250 m", quantity: "250") + self.assertDistance(275, displayed: "300 m", quantity: "300") + self.assertDistance(500, displayed: "500 m", quantity: "500") + self.assertDistance(949, displayed: "950 m", quantity: "950") + self.assertDistance(951, displayed: "950 m", quantity: "950") + self.assertDistance(999, displayed: "1 km", quantity: "1") + self.assertDistance(1000, displayed: "1 km", quantity: "1") + self.assertDistance(1001, displayed: "1 km", quantity: "1") + self.assertDistance(2500, displayed: "2.5 km", quantity: "2.5") + self.assertDistance(2900, displayed: "2.9 km", quantity: "2.9") + self.assertDistance(3000, displayed: "3 km", quantity: "3") + self.assertDistance(3500, displayed: "4 km", quantity: "4") } func testDistanceFormatters_GB() { NavigationSettings.shared.distanceUnit = .mile - distanceFormatter.numberFormatter.locale = Locale(identifier: "en-GB") + self.distanceFormatter.numberFormatter.locale = Locale(identifier: "en-GB") - assertDistance(0, displayed: "0 yd", quantity: "0") - assertDistance(oneYard * 4, displayed: "0 yd", quantity: "0") - assertDistance(oneYard * 5, displayed: "10 yd", quantity: "10") - assertDistance(oneYard * 12, displayed: "10 yd", quantity: "10") - assertDistance(oneYard * 24, displayed: "25 yd", quantity: "25") - assertDistance(oneYard * 25, displayed: "25 yd", quantity: "25") - assertDistance(oneYard * 38, displayed: "50 yd", quantity: "50") - assertDistance(oneYard * 126, displayed: "150 yd", quantity: "150") - assertDistance(oneYard * 150, displayed: "150 yd", quantity: "150") - assertDistance(oneYard * 174, displayed: "150 yd", quantity: "150") - assertDistance(oneYard * 175, displayed: "200 yd", quantity: "200") - assertDistance(oneMile / 2, displayed: "0.5 mi", quantity: "0.5") - assertDistance(oneMile, displayed: "1 mi", quantity: "1") - assertDistance(oneMile * 2.5, displayed: "2.5 mi", quantity: "2.5") - assertDistance(oneMile * 3, displayed: "3 mi", quantity: "3") + self.assertDistance(0, displayed: "0 yd", quantity: "0") + self.assertDistance(oneYard * 4, displayed: "0 yd", quantity: "0") + self.assertDistance(oneYard * 5, displayed: "10 yd", quantity: "10") + self.assertDistance(oneYard * 12, displayed: "10 yd", quantity: "10") + self.assertDistance(oneYard * 24, displayed: "25 yd", quantity: "25") + self.assertDistance(oneYard * 25, displayed: "25 yd", quantity: "25") + self.assertDistance(oneYard * 38, displayed: "50 yd", quantity: "50") + self.assertDistance(oneYard * 126, displayed: "150 yd", quantity: "150") + self.assertDistance(oneYard * 150, displayed: "150 yd", quantity: "150") + self.assertDistance(oneYard * 174, displayed: "150 yd", quantity: "150") + self.assertDistance(oneYard * 175, displayed: "200 yd", quantity: "200") + self.assertDistance(oneMile / 2, displayed: "0.5 mi", quantity: "0.5") + self.assertDistance(oneMile, displayed: "1 mi", quantity: "1") + self.assertDistance(oneMile * 2.5, displayed: "2.5 mi", quantity: "2.5") + self.assertDistance(oneMile * 3, displayed: "3 mi", quantity: "3") } func testDistanceFormatters_he_IL() { NavigationSettings.shared.distanceUnit = .kilometer - distanceFormatter.numberFormatter.locale = Locale(identifier: "he-IL") + self.distanceFormatter.numberFormatter.locale = Locale(identifier: "he-IL") - assertDistance(0, displayed: "0 מ׳", quantity: "0") - assertDistance(4, displayed: "5 מ׳", quantity: "5") - assertDistance(11, displayed: "10 מ׳", quantity: "10") - assertDistance(15, displayed: "15 מ׳", quantity: "15") - assertDistance(24, displayed: "25 מ׳", quantity: "25") - assertDistance(89, displayed: "100 מ׳", quantity: "100") - assertDistance(226, displayed: "250 מ׳", quantity: "250") - assertDistance(275, displayed: "300 מ׳", quantity: "300") - assertDistance(500, displayed: "500 מ׳", quantity: "500") - assertDistance(949, displayed: "950 מ׳", quantity: "950") - assertDistance(951, displayed: "950 מ׳", quantity: "950") + self.assertDistance(0, displayed: "0 מ׳", quantity: "0") + self.assertDistance(4, displayed: "5 מ׳", quantity: "5") + self.assertDistance(11, displayed: "10 מ׳", quantity: "10") + self.assertDistance(15, displayed: "15 מ׳", quantity: "15") + self.assertDistance(24, displayed: "25 מ׳", quantity: "25") + self.assertDistance(89, displayed: "100 מ׳", quantity: "100") + self.assertDistance(226, displayed: "250 מ׳", quantity: "250") + self.assertDistance(275, displayed: "300 מ׳", quantity: "300") + self.assertDistance(500, displayed: "500 מ׳", quantity: "500") + self.assertDistance(949, displayed: "950 מ׳", quantity: "950") + self.assertDistance(951, displayed: "950 מ׳", quantity: "950") } func testInches() { diff --git a/MapboxCoreNavigationTests/Heading.swift b/MapboxCoreNavigationTests/Heading.swift index 22797354..da5d369c 100644 --- a/MapboxCoreNavigationTests/Heading.swift +++ b/MapboxCoreNavigationTests/Heading.swift @@ -5,8 +5,8 @@ class Heading: CLHeading { private var _accuracy: CLLocationDirection init(heading: CLLocationDirection, accuracy: CLLocationDirection) { - _heading = heading - _accuracy = accuracy + self._heading = heading + self._accuracy = accuracy super.init() } @@ -17,19 +17,19 @@ class Heading: CLHeading { override open var trueHeading: CLLocationDirection { get { - _heading + self._heading } set { - _heading = newValue + self._heading = newValue } } override open var headingAccuracy: CLLocationDirection { get { - _accuracy + self._accuracy } set { - _accuracy = newValue + self._accuracy = newValue } } } diff --git a/MapboxCoreNavigationTests/LocationTests.swift b/MapboxCoreNavigationTests/LocationTests.swift index 875b22a3..4b6d692f 100644 --- a/MapboxCoreNavigationTests/LocationTests.swift +++ b/MapboxCoreNavigationTests/LocationTests.swift @@ -39,8 +39,8 @@ class LocationTests: XCTestCase { } func testSnappedLocation100MetersAlongRoute() { - let progress = setup.progress - let firstLocation = setup.firstLocation + let progress = self.setup.progress + let firstLocation = self.setup.firstLocation let initialHeadingOnFirstStep = progress.currentLegProgress.currentStep.finalHeading! let coordinateAlongFirstStep = firstLocation.coordinate.coordinate(at: 100, facing: initialHeadingOnFirstStep) @@ -53,8 +53,8 @@ class LocationTests: XCTestCase { } func testInterpolatedCourse() { - let progress = setup.progress - let firstLocation = setup.firstLocation + let progress = self.setup.progress + let firstLocation = self.setup.firstLocation let calculatedCourse = firstLocation.interpolatedCourse(along: progress.currentLegProgress.currentStepProgress.step.coordinates!)! let initialHeadingOnFirstStep = progress.currentLegProgress.currentStepProgress.step.finalHeading! @@ -62,8 +62,8 @@ class LocationTests: XCTestCase { } func testShouldSnap() { - let progress = setup.progress - let firstLocation = setup.firstLocation + let progress = self.setup.progress + let firstLocation = self.setup.firstLocation let initialHeadingOnFirstStep = progress.currentLegProgress.currentStepProgress.step.finalHeading! diff --git a/MapboxCoreNavigationTests/MapboxCoreNavigationTests.swift b/MapboxCoreNavigationTests/MapboxCoreNavigationTests.swift index 4c60454e..f203430f 100644 --- a/MapboxCoreNavigationTests/MapboxCoreNavigationTests.swift +++ b/MapboxCoreNavigationTests/MapboxCoreNavigationTests.swift @@ -20,10 +20,10 @@ class MapboxCoreNavigationTests: XCTestCase { func testDepart() { route.accessToken = "foo" - navigation = RouteController(along: route, directions: directions) + self.navigation = RouteController(along: route, directions: directions) let depart = CLLocation(coordinate: CLLocationCoordinate2D(latitude: 37.795042, longitude: -122.413165), altitude: 1, horizontalAccuracy: 1, verticalAccuracy: 1, course: 0, speed: 10, timestamp: Date()) - expectation(forNotification: .routeControllerDidPassSpokenInstructionPoint, object: navigation) { notification -> Bool in + expectation(forNotification: .routeControllerDidPassSpokenInstructionPoint, object: self.navigation) { notification -> Bool in XCTAssertEqual(notification.userInfo?.count, 1) let routeProgress = notification.userInfo![RouteControllerNotificationUserInfoKey.routeProgressKey] as? RouteProgress @@ -31,8 +31,8 @@ class MapboxCoreNavigationTests: XCTestCase { return routeProgress != nil && routeProgress?.currentLegProgress.userHasArrivedAtWaypoint == false } - navigation.resume() - navigation.locationManager(navigation.locationManager, didUpdateLocations: [depart]) + self.navigation.resume() + self.navigation.locationManager(self.navigation.locationManager, didUpdateLocations: [depart]) waitForExpectations(timeout: waitForInterval) { error in XCTAssertNil(error) @@ -46,12 +46,12 @@ class MapboxCoreNavigationTests: XCTestCase { func testNewStep() { route.accessToken = "foo" let coordOnStep1 = route.legs[0].steps[1].coordinates![5] - let location = makeLocation(latitude: coordOnStep1.latitude, longitude: coordOnStep1.longitude, course: 250) + let location = self.makeLocation(latitude: coordOnStep1.latitude, longitude: coordOnStep1.longitude, course: 250) let locationManager = ReplayLocationManager(locations: [location, location]) - navigation = RouteController(along: route, directions: directions, locationManager: locationManager) + self.navigation = RouteController(along: route, directions: directions, locationManager: locationManager) - expectation(forNotification: .routeControllerDidPassSpokenInstructionPoint, object: navigation) { notification -> Bool in + expectation(forNotification: .routeControllerDidPassSpokenInstructionPoint, object: self.navigation) { notification -> Bool in XCTAssertEqual(notification.userInfo?.count, 1) let routeProgress = notification.userInfo![RouteControllerNotificationUserInfoKey.routeProgressKey] as? RouteProgress @@ -59,7 +59,7 @@ class MapboxCoreNavigationTests: XCTestCase { return routeProgress?.currentLegProgress.stepIndex == 1 } - navigation.resume() + self.navigation.resume() waitForExpectations(timeout: waitForInterval) { error in XCTAssertNil(error) @@ -69,12 +69,12 @@ class MapboxCoreNavigationTests: XCTestCase { func testJumpAheadToLastStep() { route.accessToken = "foo" let coordOnLastStep = route.legs[0].steps[6].coordinates![5] - let location = makeLocation(latitude: coordOnLastStep.latitude, longitude: coordOnLastStep.longitude, course: 171) + let location = self.makeLocation(latitude: coordOnLastStep.latitude, longitude: coordOnLastStep.longitude, course: 171) let locationManager = ReplayLocationManager(locations: [location, location]) - navigation = RouteController(along: route, directions: directions, locationManager: locationManager) + self.navigation = RouteController(along: route, directions: directions, locationManager: locationManager) - expectation(forNotification: .routeControllerDidPassSpokenInstructionPoint, object: navigation) { notification -> Bool in + expectation(forNotification: .routeControllerDidPassSpokenInstructionPoint, object: self.navigation) { notification -> Bool in XCTAssertEqual(notification.userInfo?.count, 1) let routeProgress = notification.userInfo![RouteControllerNotificationUserInfoKey.routeProgressKey] as? RouteProgress @@ -82,7 +82,7 @@ class MapboxCoreNavigationTests: XCTestCase { return routeProgress?.currentLegProgress.stepIndex == 6 } - navigation.resume() + self.navigation.resume() waitForExpectations(timeout: waitForInterval) { error in XCTAssertNil(error) @@ -100,16 +100,16 @@ class MapboxCoreNavigationTests: XCTestCase { timestamp: Date(timeIntervalSinceNow: 1)) let locationManager = ReplayLocationManager(locations: [firstLocation, secondLocation]) - navigation = RouteController(along: route, directions: directions, locationManager: locationManager) + self.navigation = RouteController(along: route, directions: directions, locationManager: locationManager) - expectation(forNotification: .routeControllerWillReroute, object: navigation) { notification -> Bool in + expectation(forNotification: .routeControllerWillReroute, object: self.navigation) { notification -> Bool in XCTAssertEqual(notification.userInfo?.count, 1) let location = notification.userInfo![RouteControllerNotificationUserInfoKey.locationKey] as? CLLocation return location?.coordinate == secondLocation.coordinate } - navigation.resume() + self.navigation.resume() waitForExpectations(timeout: waitForInterval) { error in XCTAssertNil(error) @@ -122,14 +122,14 @@ class MapboxCoreNavigationTests: XCTestCase { let locationManager = ReplayLocationManager(locations: locations) locationManager.speedMultiplier = 20 - navigation = RouteController(along: route, directions: directions, locationManager: locationManager) + self.navigation = RouteController(along: route, directions: directions, locationManager: locationManager) - expectation(forNotification: .routeControllerProgressDidChange, object: navigation) { notification -> Bool in + expectation(forNotification: .routeControllerProgressDidChange, object: self.navigation) { notification -> Bool in let routeProgress = notification.userInfo![RouteControllerNotificationUserInfoKey.routeProgressKey] as? RouteProgress return routeProgress != nil } - navigation.resume() + self.navigation.resume() let timeout = locations.last!.timestamp.timeIntervalSince(locations.first!.timestamp) / locationManager.speedMultiplier waitForExpectations(timeout: timeout + 2) { error in @@ -140,17 +140,17 @@ class MapboxCoreNavigationTests: XCTestCase { func testFailToReroute() { route.accessToken = "foo" let directionsClientSpy = DirectionsSpy(accessToken: "garbage", host: nil) - navigation = RouteController(along: route, directions: directionsClientSpy) + self.navigation = RouteController(along: route, directions: directionsClientSpy) - expectation(forNotification: .routeControllerWillReroute, object: navigation) { _ -> Bool in + expectation(forNotification: .routeControllerWillReroute, object: self.navigation) { _ -> Bool in true } - expectation(forNotification: .routeControllerDidFailToReroute, object: navigation) { _ -> Bool in + expectation(forNotification: .routeControllerDidFailToReroute, object: self.navigation) { _ -> Bool in true } - navigation.rerouteForDiversion(from: CLLocation(latitude: 0, longitude: 0), along: navigation.routeProgress) + self.navigation.rerouteForDiversion(from: CLLocation(latitude: 0, longitude: 0), along: self.navigation.routeProgress) directionsClientSpy.fireLastCalculateCompletion(with: nil, routes: nil, error: NSError()) waitForExpectations(timeout: 2) { error in diff --git a/MapboxCoreNavigationTests/RouteControllerTests.swift b/MapboxCoreNavigationTests/RouteControllerTests.swift index bee1d0ee..8e91a0ee 100644 --- a/MapboxCoreNavigationTests/RouteControllerTests.swift +++ b/MapboxCoreNavigationTests/RouteControllerTests.swift @@ -19,7 +19,7 @@ class RouteControllerTests: XCTestCase { lazy var dependencies: (routeController: RouteController, routeLocations: RouteLocations) = { let routeController = RouteController(along: initialRoute, directions: directionsClientSpy, locationManager: NavigationLocationManager()) - routeController.delegate = delegate + routeController.delegate = self.delegate let legProgress: RouteLegProgress = routeController.routeProgress.currentLegProgress @@ -57,21 +57,21 @@ class RouteControllerTests: XCTestCase { override func setUp() { super.setUp() - directionsClientSpy.reset() - delegate.reset() + self.directionsClientSpy.reset() + self.delegate.reset() } func testUserIsOnRoute() { - let navigation = dependencies.routeController - let firstLocation = dependencies.routeLocations.firstLocation + let navigation = self.dependencies.routeController + let firstLocation = self.dependencies.routeLocations.firstLocation navigation.locationManager(navigation.locationManager, didUpdateLocations: [firstLocation]) XCTAssertTrue(navigation.userIsOnRoute(firstLocation), "User should be on route") } func testUserIsOffRoute() { - let navigation = dependencies.routeController - let firstLocation = dependencies.routeLocations.firstLocation + let navigation = self.dependencies.routeController + let firstLocation = self.dependencies.routeLocations.firstLocation let coordinateOffRoute = firstLocation.coordinate.coordinate(at: 100, facing: 90) let locationOffRoute = CLLocation(latitude: coordinateOffRoute.latitude, longitude: coordinateOffRoute.longitude) @@ -80,8 +80,8 @@ class RouteControllerTests: XCTestCase { } func testAdvancingToFutureStepAndNotRerouting() { - let navigation = dependencies.routeController - let firstLocation = dependencies.routeLocations.firstLocation + let navigation = self.dependencies.routeController + let firstLocation = self.dependencies.routeLocations.firstLocation navigation.locationManager(navigation.locationManager, didUpdateLocations: [firstLocation]) XCTAssertTrue(navigation.userIsOnRoute(firstLocation), "User should be on route") XCTAssertEqual(navigation.routeProgress.currentLegProgress.stepIndex, 0, "User is on first step") @@ -95,15 +95,15 @@ class RouteControllerTests: XCTestCase { } func testSnappedLocation() { - let navigation = dependencies.routeController - let firstLocation = dependencies.routeLocations.firstLocation + let navigation = self.dependencies.routeController + let firstLocation = self.dependencies.routeLocations.firstLocation navigation.locationManager(navigation.locationManager, didUpdateLocations: [firstLocation]) XCTAssertEqual(navigation.location!.coordinate, firstLocation.coordinate, "Check snapped location is working") } func testSnappedAtEndOfStepLocationWhenMovingSlowly() { - let navigation = dependencies.routeController - let firstLocation = dependencies.routeLocations.firstLocation + let navigation = self.dependencies.routeController + let firstLocation = self.dependencies.routeLocations.firstLocation navigation.locationManager(navigation.locationManager, didUpdateLocations: [firstLocation]) XCTAssertEqual(navigation.location!.coordinate, firstLocation.coordinate, "Check snapped location is working") @@ -120,8 +120,8 @@ class RouteControllerTests: XCTestCase { } func testSnappedAtEndOfStepLocationWhenCourseIsSimilar() { - let navigation = dependencies.routeController - let firstLocation = dependencies.routeLocations.firstLocation + let navigation = self.dependencies.routeController + let firstLocation = self.dependencies.routeLocations.firstLocation navigation.locationManager(navigation.locationManager, didUpdateLocations: [firstLocation]) XCTAssertEqual(navigation.location!.coordinate, firstLocation.coordinate, "Check snapped location is working") @@ -140,8 +140,8 @@ class RouteControllerTests: XCTestCase { } func testSnappedLocationForUnqualifiedLocation() { - let navigation = dependencies.routeController - let firstLocation = dependencies.routeLocations.firstLocation + let navigation = self.dependencies.routeController + let firstLocation = self.dependencies.routeLocations.firstLocation navigation.locationManager(navigation.locationManager, didUpdateLocations: [firstLocation]) XCTAssertEqual(navigation.location!.coordinate, firstLocation.coordinate, "Check snapped location is working") @@ -182,8 +182,8 @@ class RouteControllerTests: XCTestCase { } func testLocationShouldUseHeading() { - let navigation = dependencies.routeController - let firstLocation = dependencies.routeLocations.firstLocation + let navigation = self.dependencies.routeController + let firstLocation = self.dependencies.routeLocations.firstLocation navigation.locationManager(navigation.locationManager, didUpdateLocations: [firstLocation]) XCTAssertEqual(navigation.location!.course, firstLocation.course, "Course should be using course") @@ -201,8 +201,8 @@ class RouteControllerTests: XCTestCase { // MARK: - Events & Delegation func testReroutingFromALocationSendsEvents() { - let routeController = dependencies.routeController - let testLocation = dependencies.routeLocations.firstLocation + let routeController = self.dependencies.routeController + let testLocation = self.dependencies.routeLocations.firstLocation let willRerouteNotificationExpectation = expectation(forNotification: .routeControllerWillReroute, object: routeController) { notification -> Bool in let fromLocation = notification.userInfo![RouteControllerNotificationUserInfoKey.locationKey] as? CLLocation @@ -225,16 +225,16 @@ class RouteControllerTests: XCTestCase { // MARK: it tells the delegate & posts a willReroute notification - XCTAssertTrue(delegate.recentMessages.contains("routeController(_:willRerouteFrom:)")) + XCTAssertTrue(self.delegate.recentMessages.contains("routeController(_:willRerouteFrom:)")) wait(for: [willRerouteNotificationExpectation], timeout: 0.1) // MARK: Upon rerouting successfully... - directionsClientSpy.fireLastCalculateCompletion(with: nil, routes: [alternateRoute], error: nil) + self.directionsClientSpy.fireLastCalculateCompletion(with: nil, routes: [self.alternateRoute], error: nil) // MARK: It tells the delegate & posts a didReroute notification - XCTAssertTrue(delegate.recentMessages.contains("routeController(_:didRerouteAlong:reason:)")) + XCTAssertTrue(self.delegate.recentMessages.contains("routeController(_:didRerouteAlong:reason:)")) wait(for: [didRerouteNotificationExpectation], timeout: 0.1) // MARK: On the next call to `locationManager(_, didUpdateLocations:)` @@ -243,15 +243,15 @@ class RouteControllerTests: XCTestCase { // MARK: It tells the delegate & posts a routeProgressDidChange notification - XCTAssertTrue(delegate.recentMessages.contains("routeController(_:didUpdate:)")) + XCTAssertTrue(self.delegate.recentMessages.contains("routeController(_:didUpdate:)")) wait(for: [routeProgressDidChangeNotificationExpectation], timeout: 0.1) } func testGeneratingAnArrivalEvent() { - let routeController = dependencies.routeController - let firstLocation = dependencies.routeLocations.firstLocation - let penultimateLocation = dependencies.routeLocations.penultimateLocation - let lastLocation = dependencies.routeLocations.lastLocation + let routeController = self.dependencies.routeController + let firstLocation = self.dependencies.routeLocations.firstLocation + let penultimateLocation = self.dependencies.routeLocations.penultimateLocation + let lastLocation = self.dependencies.routeLocations.lastLocation // MARK: When navigation begins with a location update @@ -272,14 +272,14 @@ class RouteControllerTests: XCTestCase { // MARK: It tells the delegate that the user did arrive - XCTAssertTrue(delegate.recentMessages.contains("routeController(_:didArriveAt:)")) + XCTAssertTrue(self.delegate.recentMessages.contains("routeController(_:didArriveAt:)")) } func testNoReroutesAfterArriving() { - let routeController = dependencies.routeController - let firstLocation = dependencies.routeLocations.firstLocation - let penultimateLocation = dependencies.routeLocations.penultimateLocation - let lastLocation = dependencies.routeLocations.lastLocation + let routeController = self.dependencies.routeController + let firstLocation = self.dependencies.routeLocations.firstLocation + let penultimateLocation = self.dependencies.routeLocations.penultimateLocation + let lastLocation = self.dependencies.routeLocations.lastLocation // MARK: When navigation begins with a location update @@ -300,17 +300,17 @@ class RouteControllerTests: XCTestCase { // MARK: It tells the delegate that the user did arrive - XCTAssertTrue(delegate.recentMessages.contains("routeController(_:didArriveAt:)")) + XCTAssertTrue(self.delegate.recentMessages.contains("routeController(_:didArriveAt:)")) // Find a location that is very far off route let locationBeyondRoute = routeController.location!.coordinate.coordinate(at: 2000, facing: 0) routeController.locationManager(routeController.locationManager, didUpdateLocations: [CLLocation(latitude: locationBeyondRoute.latitude, longitude: locationBeyondRoute.latitude)]) // Make sure configurable delegate is called - XCTAssertTrue(delegate.recentMessages.contains("routeController(_:shouldPreventReroutesWhenArrivingAt:)")) + XCTAssertTrue(self.delegate.recentMessages.contains("routeController(_:shouldPreventReroutesWhenArrivingAt:)")) // We should not reroute here because the user has arrived. - XCTAssertFalse(delegate.recentMessages.contains("routeController(_:didRerouteAlong:)")) + XCTAssertFalse(self.delegate.recentMessages.contains("routeController(_:didRerouteAlong:)")) } func testRouteControllerDoesNotHaveRetainCycle() { @@ -329,7 +329,7 @@ class RouteControllerTests: XCTestCase { weak var subject: CLLocationManagerDelegate? = nil autoreleasepool { let locationManager = NavigationLocationManager() - _ = RouteController(along: initialRoute, directions: directionsClientSpy, locationManager: locationManager) + _ = RouteController(along: self.initialRoute, directions: self.directionsClientSpy, locationManager: locationManager) subject = locationManager.delegate } @@ -483,7 +483,7 @@ class RouteControllerTests: XCTestCase { // - Bigger detour -> 53% // --> Same route match is correct if let bestMatch = RouteController.bestMatch(for: a12ToVeenendaalNormal, and: firstRoutes) { - XCTAssertEqual(bestMatch.route, a12ToVeenendaalNormal) + XCTAssertEqual(bestMatch.route, self.a12ToVeenendaalNormal) XCTAssertEqual(bestMatch.matchPercentage, 100.0) } else { XCTFail("Should get a match above 90%") @@ -495,7 +495,7 @@ class RouteControllerTests: XCTestCase { // --> Slight difference route match is correct let secondRoutes = [a12ToVeenendaalSlightDifference, a12ToVeenendaalBiggerDetour].shuffled() if let bestMatch = RouteController.bestMatch(for: a12ToVeenendaalNormal, and: secondRoutes) { - XCTAssertEqual(bestMatch.route, a12ToVeenendaalSlightDifference) + XCTAssertEqual(bestMatch.route, self.a12ToVeenendaalSlightDifference) XCTAssertEqual(bestMatch.matchPercentage, 91.5, accuracy: 0.1) } else { XCTFail("Should get a match above 90%") @@ -513,20 +513,20 @@ class RouteControllerTests: XCTestCase { // MARK: - Applying faster/slower route func testApplyingFasterRoute() { - let routeController = dependencies.routeController + let routeController = self.dependencies.routeController let oldRouteProgress = routeController.routeProgress // Starting with route 'A12-To-Veenendaal-Normal' routeController.routeProgress = .init( - route: a12ToVeenendaalNormal, + route: self.a12ToVeenendaalNormal, legIndex: 0, spokenInstructionIndex: 0 ) // Try to apply slightly faster route 'A12-To-Veenendaal-Slight-Difference' routeController.applyNewRerouteIfNeeded( - mostSimilarRoute: a12ToVeenendaalSlightDifference, - allRoutes: [a12ToVeenendaalSlightDifference], + mostSimilarRoute: self.a12ToVeenendaalSlightDifference, + allRoutes: [self.a12ToVeenendaalSlightDifference], currentUpcomingManeuver: routeController.routeProgress.currentLegProgress.upComingStep!, durationRemaining: routeController.routeProgress.durationRemaining ) @@ -535,7 +535,7 @@ class RouteControllerTests: XCTestCase { XCTAssertEqual( routeController.routeProgress.durationRemaining, RouteProgress( - route: a12ToVeenendaalSlightDifference, + route: self.a12ToVeenendaalSlightDifference, legIndex: 0, spokenInstructionIndex: 0).durationRemaining ) @@ -545,20 +545,20 @@ class RouteControllerTests: XCTestCase { } func testNotApplyingSlowerRoute() { - let routeController = dependencies.routeController + let routeController = self.dependencies.routeController let oldRouteProgress = routeController.routeProgress // Starting with route 'A12-To-Veenendaal-Normal' routeController.routeProgress = .init( - route: a12ToVeenendaalNormal, + route: self.a12ToVeenendaalNormal, legIndex: 0, spokenInstructionIndex: 0 ) // Try to apply slower route 'A12-To-Veenendaal-Slight-Difference' routeController.applyNewRerouteIfNeeded( - mostSimilarRoute: a12ToVeenendaalBiggerDetour, - allRoutes: [a12ToVeenendaalBiggerDetour], + mostSimilarRoute: self.a12ToVeenendaalBiggerDetour, + allRoutes: [self.a12ToVeenendaalBiggerDetour], currentUpcomingManeuver: routeController.routeProgress.currentLegProgress.upComingStep!, durationRemaining: routeController.routeProgress.durationRemaining ) @@ -567,7 +567,7 @@ class RouteControllerTests: XCTestCase { XCTAssertNotEqual( routeController.routeProgress.durationRemaining, RouteProgress( - route: a12ToVeenendaalBiggerDetour, + route: self.a12ToVeenendaalBiggerDetour, legIndex: 0, spokenInstructionIndex: 0).durationRemaining ) @@ -589,20 +589,20 @@ class RouteControllerTests: XCTestCase { ) func testApplyingSlowerRoute() { - let routeController = dependencies.routeController + let routeController = self.dependencies.routeController let oldRouteProgress = routeController.routeProgress // Starting with route 'A12-To-Veenendaal-Normal' routeController.routeProgress = .init( - route: a12ToVeenendaalNormal, + route: self.a12ToVeenendaalNormal, legIndex: 0, spokenInstructionIndex: 0 ) // Try to apply slower route 'A12-To-Veenendaal-Normal-With-Big-Trafficjam' routeController.applyNewRerouteIfNeeded( - mostSimilarRoute: a12ToVeenendaalNormalWithTraffic, - allRoutes: [a12ToVeenendaalNormalWithTraffic], + mostSimilarRoute: self.a12ToVeenendaalNormalWithTraffic, + allRoutes: [self.a12ToVeenendaalNormalWithTraffic], currentUpcomingManeuver: routeController.routeProgress.currentLegProgress.upComingStep!, durationRemaining: routeController.routeProgress.durationRemaining ) @@ -611,7 +611,7 @@ class RouteControllerTests: XCTestCase { XCTAssertEqual( routeController.routeProgress.durationRemaining, RouteProgress( - route: a12ToVeenendaalNormalWithTraffic, + route: self.a12ToVeenendaalNormalWithTraffic, legIndex: 0, spokenInstructionIndex: 0).durationRemaining ) @@ -621,20 +621,20 @@ class RouteControllerTests: XCTestCase { } func testApplyingBestMatch() { - let routeController = dependencies.routeController + let routeController = self.dependencies.routeController let oldRouteProgress = routeController.routeProgress // Starting with route 'A12-To-Veenendaal-Normal' routeController.routeProgress = .init( - route: a12ToVeenendaalNormal, + route: self.a12ToVeenendaalNormal, legIndex: 0, spokenInstructionIndex: 0 ) // Try to apply slower route 'A12-To-Veenendaal-Normal-With-Big-Trafficjam' or faster route 'A12-To-Veenendaal-Slight-Difference' routeController.applyNewRerouteIfNeeded( - mostSimilarRoute: a12ToVeenendaalSlightDifference, - allRoutes: [a12ToVeenendaalNormalWithTraffic, a12ToVeenendaalSlightDifference], + mostSimilarRoute: self.a12ToVeenendaalSlightDifference, + allRoutes: [self.a12ToVeenendaalNormalWithTraffic, self.a12ToVeenendaalSlightDifference], currentUpcomingManeuver: routeController.routeProgress.currentLegProgress.upComingStep!, durationRemaining: routeController.routeProgress.durationRemaining ) @@ -643,7 +643,7 @@ class RouteControllerTests: XCTestCase { XCTAssertEqual( routeController.routeProgress.durationRemaining, RouteProgress( - route: a12ToVeenendaalNormalWithTraffic, + route: self.a12ToVeenendaalNormalWithTraffic, legIndex: 0, spokenInstructionIndex: 0).durationRemaining ) diff --git a/MapboxCoreNavigationTests/Support/DirectionsSpy.swift b/MapboxCoreNavigationTests/Support/DirectionsSpy.swift index 3fa3a058..acc8d819 100644 --- a/MapboxCoreNavigationTests/Support/DirectionsSpy.swift +++ b/MapboxCoreNavigationTests/Support/DirectionsSpy.swift @@ -11,7 +11,7 @@ class DirectionsSpy: Directions { } override func calculate(_ options: RouteOptions, completionHandler: @escaping Directions.RouteCompletionHandler) -> URLSessionDataTask { - lastCalculateOptionsCompletion = completionHandler + self.lastCalculateOptionsCompletion = completionHandler return DummyURLSessionDataTask() } @@ -30,6 +30,6 @@ class DirectionsSpy: Directions { } public func reset() { - lastCalculateOptionsCompletion = nil + self.lastCalculateOptionsCompletion = nil } } diff --git a/MapboxCoreNavigationTests/Support/RouteControllerDelegateSpy.swift b/MapboxCoreNavigationTests/Support/RouteControllerDelegateSpy.swift index ebf02d5f..d00d88e3 100644 --- a/MapboxCoreNavigationTests/Support/RouteControllerDelegateSpy.swift +++ b/MapboxCoreNavigationTests/Support/RouteControllerDelegateSpy.swift @@ -7,42 +7,42 @@ class RouteControllerDelegateSpy: RouteControllerDelegate { private(set) var recentMessages: [String] = [] public func reset() { - recentMessages.removeAll() + self.recentMessages.removeAll() } func routeController(_ routeController: RouteController, shouldRerouteFrom location: CLLocation) -> Bool { - recentMessages.append(#function) + self.recentMessages.append(#function) return true } func routeController(_ routeController: RouteController, willRerouteFrom location: CLLocation) { - recentMessages.append(#function) + self.recentMessages.append(#function) } func routeController(_ routeController: RouteController, shouldDiscard location: CLLocation) -> Bool { - recentMessages.append(#function) + self.recentMessages.append(#function) return true } func routeController(_ routeController: RouteController, didRerouteAlong route: Route, reason: RouteController.RerouteReason) { - recentMessages.append(#function) + self.recentMessages.append(#function) } func routeController(_ routeController: RouteController, didFailToRerouteWith error: Error) { - recentMessages.append(#function) + self.recentMessages.append(#function) } func routeController(_ routeController: RouteController, didUpdate locations: [CLLocation]) { - recentMessages.append(#function) + self.recentMessages.append(#function) } func routeController(_ routeController: RouteController, didArriveAt waypoint: Waypoint) -> Bool { - recentMessages.append(#function) + self.recentMessages.append(#function) return true } func routeController(_ routeController: RouteController, shouldPreventReroutesWhenArrivingAt waypoint: Waypoint) -> Bool { - recentMessages.append(#function) + self.recentMessages.append(#function) return true } } diff --git a/MapboxCoreNavigationTests/TunnelIntersectionManagerTests.swift b/MapboxCoreNavigationTests/TunnelIntersectionManagerTests.swift index 85586583..adb46d9e 100644 --- a/MapboxCoreNavigationTests/TunnelIntersectionManagerTests.swift +++ b/MapboxCoreNavigationTests/TunnelIntersectionManagerTests.swift @@ -36,9 +36,9 @@ class TunnelIntersectionManagerTests: XCTestCase { }() func testUserWithinTunnelEntranceRadius() { - let routeController = tunnelSetup.routeController + let routeController = self.tunnelSetup.routeController - routeController.tunnelIntersectionManager = tunnelSetup.tunnelIntersectionManager + routeController.tunnelIntersectionManager = self.tunnelSetup.tunnelIntersectionManager let tunnelIntersectionManager = routeController.tunnelIntersectionManager @@ -56,7 +56,7 @@ class TunnelIntersectionManagerTests: XCTestCase { var currentLocation = location(at: tunnelSetup.firstLocation.coordinate, for: routeController, intersection: tunnelIntersection, - distance: intersectionLocation.distance(to: tunnelSetup.firstLocation.coordinate)) + distance: intersectionLocation.distance(to: self.tunnelSetup.firstLocation.coordinate)) routeController.locationManager(routeController.locationManager, didUpdateLocations: [currentLocation]) @@ -68,12 +68,12 @@ class TunnelIntersectionManagerTests: XCTestCase { var userIsAtTunnelEntranceRadius = tunnelIntersectionManager.userWithinTunnelEntranceRadius(at: currentLocation, routeProgress: routeController.routeProgress) XCTAssertTrue(userIsAtTunnelEntranceRadius, "Location must be within the tunnel entrance radius") - let outsideTunnelEntranceRadius = intersectionLocation.coordinate(at: 200, facing: intersectionLocation.direction(to: tunnelSetup.firstLocation.coordinate)) + let outsideTunnelEntranceRadius = intersectionLocation.coordinate(at: 200, facing: intersectionLocation.direction(to: self.tunnelSetup.firstLocation.coordinate)) let outsideTunnelEntranceRadiusLocation = CLLocation(latitude: outsideTunnelEntranceRadius.latitude, longitude: outsideTunnelEntranceRadius.longitude) routeController.locationManager(routeController.locationManager, didUpdateLocations: [outsideTunnelEntranceRadiusLocation]) - currentLocation = location(at: tunnelSetup.firstLocation.coordinate, + currentLocation = location(at: self.tunnelSetup.firstLocation.coordinate, for: routeController, intersection: tunnelIntersection, distance: 10) @@ -83,9 +83,9 @@ class TunnelIntersectionManagerTests: XCTestCase { } func testTunnelDetected() { - let routeController = tunnelSetup.routeController + let routeController = self.tunnelSetup.routeController - routeController.tunnelIntersectionManager = tunnelSetup.tunnelIntersectionManager + routeController.tunnelIntersectionManager = self.tunnelSetup.tunnelIntersectionManager routeController.tunnelIntersectionManager.delegate = routeController // Step with a tunnel intersection @@ -105,7 +105,7 @@ class TunnelIntersectionManagerTests: XCTestCase { // Step without a tunnel intersection routeController.advanceStepIndex(to: 2) - fakeLocation = location(at: tunnelSetup.firstLocation.coordinate, for: routeController, intersection: routeController.routeProgress.currentLegProgress.currentStep.intersections![0]) + fakeLocation = location(at: self.tunnelSetup.firstLocation.coordinate, for: routeController, intersection: routeController.routeProgress.currentLegProgress.currentStep.intersections![0]) routeController.locationManager(routeController.locationManager, didUpdateLocations: [fakeLocation]) didDetectTunnel = routeController.tunnelIntersectionManager.userWithinTunnelEntranceRadius(at: routeController.location!, routeProgress: routeController.routeProgress) @@ -114,9 +114,9 @@ class TunnelIntersectionManagerTests: XCTestCase { } func testTunnelSimulatedNavigationEnabled() { - let routeController = tunnelSetup.routeController + let routeController = self.tunnelSetup.routeController - routeController.tunnelIntersectionManager = tunnelSetup.tunnelIntersectionManager + routeController.tunnelIntersectionManager = self.tunnelSetup.tunnelIntersectionManager routeController.tunnelIntersectionManager.delegate = routeController // Step with a tunnel intersection @@ -129,7 +129,7 @@ class TunnelIntersectionManagerTests: XCTestCase { let currentLocation = location(at: tunnelSetup.firstLocation.coordinate, for: routeController, intersection: tunnelIntersection, - distance: intersectionLocation.distance(to: tunnelSetup.firstLocation.coordinate)) + distance: intersectionLocation.distance(to: self.tunnelSetup.firstLocation.coordinate)) routeController.locationManager(routeController.locationManager, didUpdateLocations: [currentLocation]) @@ -144,9 +144,9 @@ class TunnelIntersectionManagerTests: XCTestCase { } func testTunnelSimulatedNavigationDisabled() { - let routeController = tunnelSetup.routeController + let routeController = self.tunnelSetup.routeController - routeController.tunnelIntersectionManager = tunnelSetup.tunnelIntersectionManager + routeController.tunnelIntersectionManager = self.tunnelSetup.tunnelIntersectionManager routeController.tunnelIntersectionManager.delegate = routeController // Step after a tunnel intersection @@ -159,7 +159,7 @@ class TunnelIntersectionManagerTests: XCTestCase { let currentLocation = location(at: tunnelSetup.firstLocation.coordinate, for: routeController, intersection: tunnelExitIntersection, - distance: intersectionLocation.distance(to: tunnelSetup.firstLocation.coordinate)) + distance: intersectionLocation.distance(to: self.tunnelSetup.firstLocation.coordinate)) routeController.locationManager(routeController.locationManager, didUpdateLocations: [currentLocation]) @@ -192,7 +192,7 @@ private extension TunnelIntersectionManagerTests { at: distance!, facing: (polyline.coordinates.first?.direction(to: intersection.location))! ) - return location(at: newLocation) + return self.location(at: newLocation) } func location(at coordinate: CLLocationCoordinate2D, horizontalAccuracy: CLLocationAccuracy? = 258.20) -> CLLocation { diff --git a/MapboxNavigation/BottomBannerView.swift b/MapboxNavigation/BottomBannerView.swift index b657dd4f..d6083ace 100644 --- a/MapboxNavigation/BottomBannerView.swift +++ b/MapboxNavigation/BottomBannerView.swift @@ -30,71 +30,71 @@ open class BottomBannerView: UIView { var congestionLevel: CongestionLevel = .unknown { didSet { - switch congestionLevel { + switch self.congestionLevel { case .unknown: - timeRemainingLabel.textColor = timeRemainingLabel.trafficUnknownColor + self.timeRemainingLabel.textColor = self.timeRemainingLabel.trafficUnknownColor case .low: - timeRemainingLabel.textColor = timeRemainingLabel.trafficLowColor + self.timeRemainingLabel.textColor = self.timeRemainingLabel.trafficLowColor case .moderate: - timeRemainingLabel.textColor = timeRemainingLabel.trafficModerateColor + self.timeRemainingLabel.textColor = self.timeRemainingLabel.trafficModerateColor case .heavy: - timeRemainingLabel.textColor = timeRemainingLabel.trafficHeavyColor + self.timeRemainingLabel.textColor = self.timeRemainingLabel.trafficHeavyColor case .severe: - timeRemainingLabel.textColor = timeRemainingLabel.trafficSevereColor + self.timeRemainingLabel.textColor = self.timeRemainingLabel.trafficSevereColor } } } override init(frame: CGRect) { super.init(frame: frame) - commonInit() + self.commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) - commonInit() + self.commonInit() } func commonInit() { - dateFormatter.timeStyle = .short - dateComponentsFormatter.allowedUnits = [.hour, .minute] - dateComponentsFormatter.unitsStyle = .abbreviated + self.dateFormatter.timeStyle = .short + self.dateComponentsFormatter.allowedUnits = [.hour, .minute] + self.dateComponentsFormatter.unitsStyle = .abbreviated setupViews() - cancelButton.addTarget(self, action: #selector(BottomBannerView.cancel(_:)), for: .touchUpInside) + self.cancelButton.addTarget(self, action: #selector(BottomBannerView.cancel(_:)), for: .touchUpInside) } @IBAction func cancel(_ sender: Any) { - delegate?.didCancel() + self.delegate?.didCancel() } override open func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() - timeRemainingLabel.text = "22 min" - distanceRemainingLabel.text = "4 mi" - arrivalTimeLabel.text = "10:09" + self.timeRemainingLabel.text = "22 min" + self.distanceRemainingLabel.text = "4 mi" + self.arrivalTimeLabel.text = "10:09" } func updateETA(routeProgress: RouteProgress) { guard let arrivalDate = NSCalendar.current.date(byAdding: .second, value: Int(routeProgress.durationRemaining), to: Date()) else { return } - arrivalTimeLabel.text = dateFormatter.string(from: arrivalDate) + self.arrivalTimeLabel.text = self.dateFormatter.string(from: arrivalDate) if routeProgress.durationRemaining < 5 { - distanceRemainingLabel.text = nil + self.distanceRemainingLabel.text = nil } else { - distanceRemainingLabel.text = distanceFormatter.string(from: routeProgress.distanceRemaining) + self.distanceRemainingLabel.text = self.distanceFormatter.string(from: routeProgress.distanceRemaining) } - dateComponentsFormatter.unitsStyle = routeProgress.durationRemaining < 3600 ? .short : .abbreviated + self.dateComponentsFormatter.unitsStyle = routeProgress.durationRemaining < 3600 ? .short : .abbreviated if let hardcodedTime = dateComponentsFormatter.string(from: 61), routeProgress.durationRemaining < 60 { - timeRemainingLabel.text = String.localizedStringWithFormat(NSLocalizedString("LESS_THAN", bundle: .mapboxNavigation, value: "<%@", comment: "Format string for a short distance or time less than a minimum threshold; 1 = duration remaining"), hardcodedTime) + self.timeRemainingLabel.text = String.localizedStringWithFormat(NSLocalizedString("LESS_THAN", bundle: .mapboxNavigation, value: "<%@", comment: "Format string for a short distance or time less than a minimum threshold; 1 = duration remaining"), hardcodedTime) } else { - timeRemainingLabel.text = dateComponentsFormatter.string(from: routeProgress.durationRemaining) + self.timeRemainingLabel.text = self.dateComponentsFormatter.string(from: routeProgress.durationRemaining) } guard let congestionForRemainingLeg = routeProgress.averageCongestionLevelRemainingOnLeg else { return } - congestionLevel = congestionForRemainingLeg + self.congestionLevel = congestionForRemainingLeg } } diff --git a/MapboxNavigation/BottomBannerViewLayout.swift b/MapboxNavigation/BottomBannerViewLayout.swift index 0fd2a550..4a25fe58 100644 --- a/MapboxNavigation/BottomBannerViewLayout.swift +++ b/MapboxNavigation/BottomBannerViewLayout.swift @@ -35,12 +35,12 @@ extension BottomBannerView { addSubview(horizontalDividerView) self.horizontalDividerView = horizontalDividerView - setupConstraints() + self.setupConstraints() } private func setupConstraints() { - setupVerticalCompactLayout(&verticalCompactConstraints) - setupVerticalRegularLayout(&verticalRegularConstraints) + self.setupVerticalCompactLayout(&verticalCompactConstraints) + self.setupVerticalRegularLayout(&verticalRegularConstraints) } private func setupVerticalCompactLayout(_ c: inout [NSLayoutConstraint]) { diff --git a/MapboxNavigation/Cache.swift b/MapboxNavigation/Cache.swift index 2d74693d..14e6c2d1 100644 --- a/MapboxNavigation/Cache.swift +++ b/MapboxNavigation/Cache.swift @@ -44,8 +44,8 @@ class FileCache { var fileManager: FileManager? init() { - diskAccessQueue.sync { - fileManager = FileManager() + self.diskAccessQueue.sync { + self.fileManager = FileManager() } } @@ -58,7 +58,7 @@ class FileCache { return } - diskAccessQueue.async { + self.diskAccessQueue.async { self.createCacheDirIfNeeded(self.diskCacheURL, fileManager: fileManager) let cacheURL = self.cacheURLWithKey(key) @@ -80,7 +80,7 @@ class FileCache { } do { - return try Data(contentsOf: cacheURLWithKey(key)) + return try Data(contentsOf: self.cacheURLWithKey(key)) } catch { return nil } @@ -94,8 +94,8 @@ class FileCache { return } - let cacheURL = diskCacheURL - diskAccessQueue.async { + let cacheURL = self.diskCacheURL + self.diskAccessQueue.async { do { try fileManager.removeItem(at: cacheURL) } catch { @@ -109,13 +109,13 @@ class FileCache { } func cachePathWithKey(_ key: String) -> String { - let cacheKey = cacheKeyForKey(key) - return cacheURLWithKey(cacheKey).absoluteString + let cacheKey = self.cacheKeyForKey(key) + return self.cacheURLWithKey(cacheKey).absoluteString } func cacheURLWithKey(_ key: String) -> URL { - let cacheKey = cacheKeyForKey(key) - return diskCacheURL.appendingPathComponent(cacheKey) + let cacheKey = self.cacheKeyForKey(key) + return self.diskCacheURL.appendingPathComponent(cacheKey) } func cacheKeyForKey(_ key: String) -> String { diff --git a/MapboxNavigation/CarPlayManager+Search.swift b/MapboxNavigation/CarPlayManager+Search.swift index 9d1747d9..9bd3346f 100644 --- a/MapboxNavigation/CarPlayManager+Search.swift +++ b/MapboxNavigation/CarPlayManager+Search.swift @@ -66,7 +66,7 @@ extension CarPlayManager: CPSearchTemplateDelegate { CarPlayManager.shared.recentSearchText = searchText // Append recent searches - var items = recentSearches(searchText) + var items = self.recentSearches(searchText) // Search for placemarks using MapboxGeocoder.swift let shouldSearch = searchText.count > 2 @@ -74,17 +74,17 @@ extension CarPlayManager: CPSearchTemplateDelegate { let options = CarPlayManager.forwardGeocodeOptions(searchText) Geocoder.shared.geocode(options, completionHandler: { placemarks, _, _ in guard let placemarks else { - completionHandler(CarPlayManager.resultsOrNoResults(items, limit: MaximumInitialSearchResults)) + completionHandler(CarPlayManager.resultsOrNoResults(items, limit: self.MaximumInitialSearchResults)) return } let results = placemarks.map { $0.listItem() } items.append(contentsOf: results) - completionHandler(CarPlayManager.resultsOrNoResults(results, limit: MaximumInitialSearchResults)) + completionHandler(CarPlayManager.resultsOrNoResults(results, limit: self.MaximumInitialSearchResults)) }) } else { - completionHandler(CarPlayManager.resultsOrNoResults(items, limit: MaximumInitialSearchResults)) + completionHandler(CarPlayManager.resultsOrNoResults(items, limit: self.MaximumInitialSearchResults)) } } @@ -110,8 +110,8 @@ extension CarPlayManager: CPSearchTemplateDelegate { return } - recentItems.add(RecentItem(placemark)) - recentItems.save() + self.recentItems.add(RecentItem(placemark)) + self.recentItems.save() let destinationWaypoint = Waypoint(location: location, heading: nil, name: placemark.formattedName) CarPlayManager.shared.calculateRouteAndStart(to: destinationWaypoint, completionHandler: completionHandler) @@ -120,9 +120,9 @@ extension CarPlayManager: CPSearchTemplateDelegate { @available(iOS 12.0, *) static func recentSearches(_ searchText: String) -> [CPListItem] { if searchText.isEmpty { - return recentItems.map { $0.geocodedPlacemark.listItem() } + return self.recentItems.map { $0.geocodedPlacemark.listItem() } } - return recentItems.filter { $0.matches(searchText) }.map { $0.geocodedPlacemark.listItem() } + return self.recentItems.filter { $0.matches(searchText) }.map { $0.geocodedPlacemark.listItem() } } @available(iOS 12.0, *) diff --git a/MapboxNavigation/CarPlayManager.swift b/MapboxNavigation/CarPlayManager.swift index 61cb3bdc..e600264f 100644 --- a/MapboxNavigation/CarPlayManager.swift +++ b/MapboxNavigation/CarPlayManager.swift @@ -176,7 +176,7 @@ public class CarPlayManager: NSObject { public static let CarPlayWaypointKey: String = "MBCarPlayWaypoint" public static func resetSharedInstance() { - shared = CarPlayManager() + self.shared = CarPlayManager() } /** @@ -223,7 +223,7 @@ public class CarPlayManager: NSObject { @available(iOS 12.0, *) extension CarPlayManager: CPApplicationDelegate { public func application(_ application: UIApplication, didConnectCarInterfaceController interfaceController: CPInterfaceController, to window: CPWindow) { - isConnectedToCarPlay = true + self.isConnectedToCarPlay = true interfaceController.delegate = self self.interfaceController = interfaceController @@ -235,17 +235,17 @@ extension CarPlayManager: CPApplicationDelegate { let viewController = CarPlayMapViewController() window.rootViewController = viewController - carWindow = window + self.carWindow = window let mapTemplate = mapTemplate(for: interfaceController, viewController: viewController) - mainMapTemplate = mapTemplate + self.mainMapTemplate = mapTemplate interfaceController.setRootTemplate(mapTemplate, animated: false) } public func application(_ application: UIApplication, didDisconnectCarInterfaceController interfaceController: CPInterfaceController, from window: CPWindow) { - isConnectedToCarPlay = false + self.isConnectedToCarPlay = false self.interfaceController = nil - carWindow?.isHidden = true + self.carWindow?.isHidden = true if let shouldDisableIdleTimer = delegate?.carplayManagerShouldDisableIdleTimer?(self) { UIApplication.shared.isIdleTimerDisabled = !shouldDisableIdleTimer @@ -279,7 +279,7 @@ extension CarPlayManager: CPApplicationDelegate { if let mapButtons = delegate?.carPlayManager?(self, mapButtonsCompatibleWith: traitCollection, in: mapTemplate, for: .browsing) { mapTemplate.mapButtons = mapButtons } else if let vc = viewController as? CarPlayMapViewController { - mapTemplate.mapButtons = [vc.recenterButton, panMapButton(for: mapTemplate, traitCollection: traitCollection), vc.zoomInButton(), vc.zoomOutButton()] + mapTemplate.mapButtons = [vc.recenterButton, self.panMapButton(for: mapTemplate, traitCollection: traitCollection), vc.zoomInButton(), vc.zoomOutButton()] } return mapTemplate @@ -334,14 +334,14 @@ extension CarPlayManager: CPApplicationDelegate { @available(iOS 12.0, *) extension CarPlayManager: CPInterfaceControllerDelegate { public func templateWillAppear(_ template: CPTemplate, animated: Bool) { - if template == interfaceController?.rootTemplate, let carPlayMapViewController = carWindow?.rootViewController as? CarPlayMapViewController { + if template == self.interfaceController?.rootTemplate, let carPlayMapViewController = carWindow?.rootViewController as? CarPlayMapViewController { carPlayMapViewController.recenterButton.isHidden = true } } public func templateDidAppear(_ template: CPTemplate, animated: Bool) { - guard interfaceController?.topTemplate == mainMapTemplate else { return } - if template == interfaceController?.rootTemplate, let carPlayMapViewController = carWindow?.rootViewController as? CarPlayMapViewController { + guard self.interfaceController?.topTemplate == self.mainMapTemplate else { return } + if template == self.interfaceController?.rootTemplate, let carPlayMapViewController = carWindow?.rootViewController as? CarPlayMapViewController { let mapView = carPlayMapViewController.mapView mapView.removeRoutes() mapView.removeWaypoints() @@ -374,8 +374,8 @@ extension CarPlayManager: CPListTemplateDelegate { let placemark = userInfo[CarPlayManager.CarPlayGeocodedPlacemarkKey] as? GeocodedPlacemark, let location = placemark.location { let destinationWaypoint = Waypoint(location: location) - interfaceController?.popTemplate(animated: false) - calculateRouteAndStart(to: destinationWaypoint, completionHandler: completionHandler) + self.interfaceController?.popTemplate(animated: false) + self.calculateRouteAndStart(to: destinationWaypoint, completionHandler: completionHandler) return } #endif @@ -383,7 +383,7 @@ extension CarPlayManager: CPListTemplateDelegate { // Selected a favorite? or any item with a waypoint. if let userInfo = item.userInfo as? [String: Any], let waypoint = userInfo[CarPlayManager.CarPlayWaypointKey] as? Waypoint { - calculateRouteAndStart(to: waypoint, completionHandler: completionHandler) + self.calculateRouteAndStart(to: waypoint, completionHandler: completionHandler) return } @@ -458,7 +458,7 @@ extension CarPlayManager: CPListTemplateDelegate { } func mapTemplate(forPreviewing trip: CPTrip) -> CPMapTemplate { - let rootViewController = carWindow?.rootViewController as! CarPlayMapViewController + let rootViewController = self.carWindow?.rootViewController as! CarPlayMapViewController let mapTemplate = CPMapTemplate() mapTemplate.mapDelegate = self if let leadingButtons = delegate?.carPlayManager?(self, leadingNavigationBarButtonsCompatibleWith: rootViewController.traitCollection, in: mapTemplate, for: .previewing) { @@ -487,7 +487,7 @@ extension CarPlayManager: CPMapTemplateDelegate { let routeController: RouteController = if let routeControllerFromDelegate = delegate?.carPlayManager?(self, routeControllerAlong: route) { routeControllerFromDelegate } else { - createRouteController(with: route) + self.createRouteController(with: route) } interfaceController.popToRootTemplate(animated: false) @@ -499,7 +499,7 @@ extension CarPlayManager: CPMapTemplateDelegate { interfaceController: interfaceController) navigationViewController.startNavigationSession(for: trip) navigationViewController.carPlayNavigationDelegate = self - currentNavigator = navigationViewController + self.currentNavigator = navigationViewController carPlayMapViewController.isOverviewingRoutes = false carPlayMapViewController.present(navigationViewController, animated: true, completion: nil) @@ -508,7 +508,7 @@ extension CarPlayManager: CPMapTemplateDelegate { mapView.removeRoutes() mapView.removeWaypoints() - delegate?.carPlayManager(self, didBeginNavigationWith: routeController) + self.delegate?.carPlayManager(self, didBeginNavigationWith: routeController) } func mapTemplate(forNavigating trip: CPTrip) -> CPMapTemplate { @@ -585,7 +585,7 @@ extension CarPlayManager: CPMapTemplateDelegate { let mapView = carPlayMapViewController.mapView mapView.removeRoutes() mapView.removeWaypoints() - delegate?.carPlayManagerDidEndNavigation(self) + self.delegate?.carPlayManagerDidEndNavigation(self) } public func mapTemplateDidBeginPanGesture(_ mapTemplate: CPMapTemplate) { @@ -595,7 +595,7 @@ extension CarPlayManager: CPMapTemplateDelegate { } public func mapTemplate(_ mapTemplate: CPMapTemplate, didEndPanGestureWithVelocity velocity: CGPoint) { - if mapTemplate == interfaceController?.rootTemplate, let carPlayMapViewController = carWindow?.rootViewController as? CarPlayMapViewController { + if mapTemplate == self.interfaceController?.rootTemplate, let carPlayMapViewController = carWindow?.rootViewController as? CarPlayMapViewController { carPlayMapViewController.recenterButton.isHidden = carPlayMapViewController.mapView.userTrackingMode != .none } @@ -606,7 +606,7 @@ extension CarPlayManager: CPMapTemplateDelegate { let decelerationRate: CGFloat = 0.9 let offset = CGPoint(x: velocity.x * decelerationRate / 4, y: velocity.y * decelerationRate / 4) - updatePan(by: offset, mapTemplate: mapTemplate, animated: true) + self.updatePan(by: offset, mapTemplate: mapTemplate, animated: true) } public func mapTemplateWillDismissPanningInterface(_ mapTemplate: CPMapTemplate) { @@ -629,7 +629,7 @@ extension CarPlayManager: CPMapTemplateDelegate { } mapView.setContentInset(mapView.safeArea, animated: false, completionHandler: nil) // make sure this is always up to date in-case safe area changes during gesture - updatePan(by: translation, mapTemplate: mapTemplate, animated: false) + self.updatePan(by: translation, mapTemplate: mapTemplate, animated: false) } private func updatePan(by offset: CGPoint, mapTemplate: CPMapTemplate, animated: Bool) { @@ -679,9 +679,9 @@ extension CarPlayManager: CPMapTemplateDelegate { } private func createRouteController(with route: Route) -> RouteController { - if simulatesLocations { + if self.simulatesLocations { let locationManager = SimulatedLocationManager(route: route) - locationManager.speedMultiplier = simulatedSpeedMultiplier + locationManager.speedMultiplier = self.simulatedSpeedMultiplier return RouteController(along: route, locationManager: locationManager) } else { return RouteController(along: route) @@ -694,15 +694,15 @@ extension CarPlayManager: CPMapTemplateDelegate { @available(iOS 12.0, *) extension CarPlayManager: CarPlayNavigationDelegate { public func carPlayNavigationViewControllerDidArrive(_: CarPlayNavigationViewController) { - delegate?.carPlayManagerDidEndNavigation(self) + self.delegate?.carPlayManagerDidEndNavigation(self) } public func carPlayNavigationViewControllerDidDismiss(_ carPlayNavigationViewController: CarPlayNavigationViewController, byCanceling canceled: Bool) { if let mainMapTemplate { - interfaceController?.setRootTemplate(mainMapTemplate, animated: true) + self.interfaceController?.setRootTemplate(mainMapTemplate, animated: true) } - interfaceController?.popToRootTemplate(animated: true) - delegate?.carPlayManagerDidEndNavigation(self) + self.interfaceController?.popToRootTemplate(animated: true) + self.delegate?.carPlayManagerDidEndNavigation(self) } } #else diff --git a/MapboxNavigation/CarPlayMapViewController.swift b/MapboxNavigation/CarPlayMapViewController.swift index 1321bb19..79e4a6a7 100644 --- a/MapboxNavigation/CarPlayMapViewController.swift +++ b/MapboxNavigation/CarPlayMapViewController.swift @@ -49,11 +49,11 @@ class CarPlayMapViewController: UIViewController, MLNMapViewDelegate { override func viewDidLoad() { super.viewDidLoad() - styleManager = StyleManager(self) - styleManager.styles = [DayStyle(), NightStyle()] + self.styleManager = StyleManager(self) + self.styleManager.styles = [DayStyle(), NightStyle()] - resetCamera(animated: false, altitude: CarPlayMapViewController.defaultAltitude) - mapView.setUserTrackingMode(.followWithCourse, animated: true, completionHandler: nil) + self.resetCamera(animated: false, altitude: CarPlayMapViewController.defaultAltitude) + self.mapView.setUserTrackingMode(.followWithCourse, animated: true, completionHandler: nil) } public func zoomInButton() -> CPMapButton { @@ -89,18 +89,18 @@ class CarPlayMapViewController: UIViewController, MLNMapViewDelegate { } func resetCamera(animated: Bool = false, altitude: CLLocationDistance? = nil) { - let camera = mapView.camera + let camera = self.mapView.camera if let altitude { camera.altitude = altitude } camera.pitch = 60 - mapView.setCamera(camera, animated: animated) + self.mapView.setCamera(camera, animated: animated) } override func viewSafeAreaInsetsDidChange() { - mapView.setContentInset(mapView.safeArea, animated: false, completionHandler: nil) + self.mapView.setContentInset(self.mapView.safeArea, animated: false, completionHandler: nil) - guard isOverviewingRoutes else { + guard self.isOverviewingRoutes else { super.viewSafeAreaInsetsDidChange() return } @@ -111,26 +111,26 @@ class CarPlayMapViewController: UIViewController, MLNMapViewDelegate { return } - mapView.fit(to: active, animated: false) + self.mapView.fit(to: active, animated: false) } } @available(iOS 12.0, *) extension CarPlayMapViewController: StyleManagerDelegate { func locationFor(styleManager: StyleManager) -> CLLocation? { - mapView.userLocationForCourseTracking ?? mapView.userLocation?.location ?? coarseLocationManager.location + self.mapView.userLocationForCourseTracking ?? self.mapView.userLocation?.location ?? self.coarseLocationManager.location } func styleManager(_ styleManager: StyleManager, didApply style: Style) { let styleURL = style.previewMapStyleURL - if mapView.styleURL != styleURL { - mapView.style?.transition = MLNTransition(duration: 0.5, delay: 0) - mapView.styleURL = styleURL + if self.mapView.styleURL != styleURL { + self.mapView.style?.transition = MLNTransition(duration: 0.5, delay: 0) + self.mapView.styleURL = styleURL } } func styleManagerDidRefreshAppearance(_ styleManager: StyleManager) { - mapView.reloadStyle(self) + self.mapView.reloadStyle(self) } } #endif diff --git a/MapboxNavigation/CarPlayNavigationViewController.swift b/MapboxNavigation/CarPlayNavigationViewController.swift index 319e3fd8..7789e380 100644 --- a/MapboxNavigation/CarPlayNavigationViewController.swift +++ b/MapboxNavigation/CarPlayNavigationViewController.swift @@ -56,7 +56,7 @@ public class CarPlayNavigationViewController: UIViewController, MLNMapViewDelega interfaceController: CPInterfaceController) { self.routeController = routeController self.mapTemplate = mapTemplate - carInterfaceController = interfaceController + self.carInterfaceController = interfaceController super.init(nibName: nil, bundle: nil) routeController.delegate = self @@ -84,23 +84,23 @@ public class CarPlayNavigationViewController: UIViewController, MLNMapViewDelega self.mapView = mapView view.addSubview(mapView) - styleManager = StyleManager(self) - styleManager.styles = [DayStyle(), NightStyle()] + self.styleManager = StyleManager(self) + self.styleManager.styles = [DayStyle(), NightStyle()] - resumeNotifications() - routeController.resume() + self.resumeNotifications() + self.routeController.resume() mapView.recenterMap() } override public func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) - suspendNotifications() + self.suspendNotifications() } func resumeNotifications() { - NotificationCenter.default.addObserver(self, selector: #selector(progressDidChange(_:)), name: .routeControllerProgressDidChange, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(rerouted(_:)), name: .routeControllerDidReroute, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(visualInstructionDidChange(_:)), name: .routeControllerDidPassVisualInstructionPoint, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(self.progressDidChange(_:)), name: .routeControllerProgressDidChange, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(self.rerouted(_:)), name: .routeControllerDidReroute, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(self.visualInstructionDidChange(_:)), name: .routeControllerDidPassVisualInstructionPoint, object: nil) } func suspendNotifications() { @@ -114,7 +114,7 @@ public class CarPlayNavigationViewController: UIViewController, MLNMapViewDelega if let previousSafeAreaInsets { let navigationBarIsOpen = view.safeAreaInsets > previousSafeAreaInsets - mapView?.compassView.isHidden = navigationBarIsOpen + self.mapView?.compassView.isHidden = navigationBarIsOpen } previousSafeAreaInsets = view.safeAreaInsets @@ -127,7 +127,7 @@ public class CarPlayNavigationViewController: UIViewController, MLNMapViewDelega */ @objc(startNavigationSessionForTrip:) public func startNavigationSession(for trip: CPTrip) { - carSession = mapTemplate.startNavigationSession(for: trip) + self.carSession = self.mapTemplate.startNavigationSession(for: trip) } /** @@ -137,16 +137,16 @@ public class CarPlayNavigationViewController: UIViewController, MLNMapViewDelega */ @objc(exitNavigationByCanceling:) public func exitNavigation(byCanceling canceled: Bool = false) { - carSession.finishTrip() + self.carSession.finishTrip() dismiss(animated: true, completion: nil) - carPlayNavigationDelegate?.carPlayNavigationViewControllerDidDismiss(self, byCanceling: canceled) + self.carPlayNavigationDelegate?.carPlayNavigationViewControllerDidDismiss(self, byCanceling: canceled) } /** Shows the interface for providing feedback about the route. */ @objc public func showFeedback() { - carInterfaceController.pushTemplate(carFeedbackTemplate, animated: true) + self.carInterfaceController.pushTemplate(self.carFeedbackTemplate, animated: true) } /** @@ -156,41 +156,41 @@ public class CarPlayNavigationViewController: UIViewController, MLNMapViewDelega */ @objc public var tracksUserCourse: Bool { get { - mapView?.tracksUserCourse ?? false + self.mapView?.tracksUserCourse ?? false } set { if !tracksUserCourse, newValue { - mapView?.recenterMap() - mapView?.addArrow(route: routeController.routeProgress.route, - legIndex: routeController.routeProgress.legIndex, - stepIndex: routeController.routeProgress.currentLegProgress.stepIndex + 1) + self.mapView?.recenterMap() + self.mapView?.addArrow(route: self.routeController.routeProgress.route, + legIndex: self.routeController.routeProgress.legIndex, + stepIndex: self.routeController.routeProgress.currentLegProgress.stepIndex + 1) } else if tracksUserCourse, !newValue { guard let userLocation = routeController.locationManager.location?.coordinate else { return } - mapView?.enableFrameByFrameCourseViewTracking(for: 3) - mapView?.setOverheadCameraView(from: userLocation, along: routeController.routeProgress.route.coordinates!, for: edgePadding) + self.mapView?.enableFrameByFrameCourseViewTracking(for: 3) + self.mapView?.setOverheadCameraView(from: userLocation, along: self.routeController.routeProgress.route.coordinates!, for: self.edgePadding) } } } public func beginPanGesture() { - mapView?.tracksUserCourse = false - mapView?.enableFrameByFrameCourseViewTracking(for: 1) + self.mapView?.tracksUserCourse = false + self.mapView?.enableFrameByFrameCourseViewTracking(for: 1) } public func mapView(_ mapView: MLNMapView, didFinishLoading style: MLNStyle) { - self.mapView?.addArrow(route: routeController.routeProgress.route, legIndex: routeController.routeProgress.legIndex, stepIndex: routeController.routeProgress.currentLegProgress.stepIndex + 1) - self.mapView?.showRoutes([routeController.routeProgress.route]) - self.mapView?.showWaypoints(routeController.routeProgress.route) + self.mapView?.addArrow(route: self.routeController.routeProgress.route, legIndex: self.routeController.routeProgress.legIndex, stepIndex: self.routeController.routeProgress.currentLegProgress.stepIndex + 1) + self.mapView?.showRoutes([self.routeController.routeProgress.route]) + self.mapView?.showWaypoints(self.routeController.routeProgress.route) self.mapView?.recenterMap() } @objc func visualInstructionDidChange(_ notification: NSNotification) { let routeProgress = notification.userInfo![RouteControllerNotificationUserInfoKey.routeProgressKey] as! RouteProgress - updateManeuvers(for: routeProgress) - mapView?.showWaypoints(routeProgress.route) - mapView?.addArrow(route: routeProgress.route, legIndex: routeProgress.legIndex, stepIndex: routeProgress.currentLegProgress.stepIndex + 1) + self.updateManeuvers(for: routeProgress) + self.mapView?.showWaypoints(routeProgress.route) + self.mapView?.addArrow(route: routeProgress.route, legIndex: routeProgress.legIndex, stepIndex: routeProgress.currentLegProgress.stepIndex + 1) } @objc func progressDidChange(_ notification: NSNotification) { @@ -199,39 +199,39 @@ public class CarPlayNavigationViewController: UIViewController, MLNMapViewDelega // Update the user puck let camera = MLNMapCamera(lookingAtCenter: location.coordinate, acrossDistance: 120, pitch: 60, heading: location.course) - mapView?.updateCourseTracking(location: location, camera: camera, animated: true) + self.mapView?.updateCourseTracking(location: location, camera: camera, animated: true) let congestionLevel = routeProgress.averageCongestionLevelRemainingOnLeg ?? .unknown guard let maneuver = carSession.upcomingManeuvers.first else { return } let legProgress = routeProgress.currentLegProgress - let legDistance = distanceFormatter.measurement(of: legProgress.distanceRemaining) + let legDistance = self.distanceFormatter.measurement(of: legProgress.distanceRemaining) let legEstimates = CPTravelEstimates(distanceRemaining: legDistance, timeRemaining: legProgress.durationRemaining) - mapTemplate.update(legEstimates, for: carSession.trip, with: congestionLevel.asCPTimeRemainingColor) + self.mapTemplate.update(legEstimates, for: self.carSession.trip, with: congestionLevel.asCPTimeRemainingColor) let stepProgress = legProgress.currentStepProgress - let stepDistance = distanceFormatter.measurement(of: stepProgress.distanceRemaining) + let stepDistance = self.distanceFormatter.measurement(of: stepProgress.distanceRemaining) let stepEstimates = CPTravelEstimates(distanceRemaining: stepDistance, timeRemaining: stepProgress.durationRemaining) - carSession.updateEstimates(stepEstimates, for: maneuver) + self.carSession.updateEstimates(stepEstimates, for: maneuver) } @objc func rerouted(_ notification: NSNotification) { - updateRouteOnMap() - mapView?.recenterMap() + self.updateRouteOnMap() + self.mapView?.recenterMap() } func updateRouteOnMap() { - mapView?.addArrow(route: routeController.routeProgress.route, legIndex: routeController.routeProgress.legIndex, stepIndex: routeController.routeProgress.currentLegProgress.stepIndex + 1) - mapView?.showRoutes([routeController.routeProgress.route], legIndex: routeController.routeProgress.legIndex) - mapView?.showWaypoints(routeController.routeProgress.route, legIndex: routeController.routeProgress.legIndex) + self.mapView?.addArrow(route: self.routeController.routeProgress.route, legIndex: self.routeController.routeProgress.legIndex, stepIndex: self.routeController.routeProgress.currentLegProgress.stepIndex + 1) + self.mapView?.showRoutes([self.routeController.routeProgress.route], legIndex: self.routeController.routeProgress.legIndex) + self.mapView?.showWaypoints(self.routeController.routeProgress.route, legIndex: self.routeController.routeProgress.legIndex) } func updateManeuvers(for routeProgress: RouteProgress) { guard let visualInstruction = routeProgress.currentLegProgress.currentStepProgress.currentVisualInstruction else { return } - let step = routeController.routeProgress.currentLegProgress.currentStep + let step = self.routeController.routeProgress.currentLegProgress.currentStep let primaryManeuver = CPManeuver() - let distance = distanceFormatter.measurement(of: step.distance) + let distance = self.distanceFormatter.measurement(of: step.distance) primaryManeuver.initialTravelEstimates = CPTravelEstimates(distanceRemaining: distance, timeRemaining: step.expectedTravelTime) // Just incase, set some default text @@ -279,14 +279,14 @@ public class CarPlayNavigationViewController: UIViewController, MLNMapViewDelega } if let upcomingStep = routeController.routeProgress.currentLegProgress.upComingStep { - let distance = distanceFormatter.measurement(of: upcomingStep.distance) + let distance = self.distanceFormatter.measurement(of: upcomingStep.distance) tertiaryManeuver.initialTravelEstimates = CPTravelEstimates(distanceRemaining: distance, timeRemaining: upcomingStep.expectedTravelTime) } maneuvers.append(tertiaryManeuver) } - carSession.upcomingManeuvers = maneuvers + self.carSession.upcomingManeuvers = maneuvers } func endOfRouteFeedbackTemplate() -> CPGridTemplate { @@ -321,7 +321,7 @@ public class CarPlayNavigationViewController: UIViewController, MLNMapViewDelega let arrivalTitle = NSLocalizedString("CARPLAY_ARRIVED", bundle: .mapboxNavigation, value: "You have arrived", comment: "Title on arrival action sheet") let arrivalMessage = NSLocalizedString("CARPLAY_ARRIVED_MESSAGE", bundle: .mapboxNavigation, value: "What would you like to do?", comment: "Message on arrival action sheet") let alert = CPActionSheetTemplate(title: arrivalTitle, message: arrivalMessage, actions: [rateAction, exitAction]) - carInterfaceController.presentTemplate(alert, animated: true) + self.carInterfaceController.presentTemplate(alert, animated: true) } func presentWayointArrivalUI(for waypoint: Waypoint) { @@ -338,25 +338,25 @@ public class CarPlayNavigationViewController: UIViewController, MLNMapViewDelega } let waypointArrival = CPAlertTemplate(titleVariants: [title], actions: [continueAlert]) - carInterfaceController.presentTemplate(waypointArrival, animated: true) + self.carInterfaceController.presentTemplate(waypointArrival, animated: true) } } @available(iOS 12.0, *) extension CarPlayNavigationViewController: StyleManagerDelegate { public func locationFor(styleManager: StyleManager) -> CLLocation? { - routeController.locationManager.location + self.routeController.locationManager.location } public func styleManager(_ styleManager: StyleManager, didApply style: Style) { - if mapView?.styleURL != style.mapStyleURL { - mapView?.style?.transition = MLNTransition(duration: 0.5, delay: 0) - mapView?.styleURL = style.mapStyleURL + if self.mapView?.styleURL != style.mapStyleURL { + self.mapView?.style?.transition = MLNTransition(duration: 0.5, delay: 0) + self.mapView?.styleURL = style.mapStyleURL } } public func styleManagerDidRefreshAppearance(_ styleManager: StyleManager) { - mapView?.reloadStyle(self) + self.mapView?.reloadStyle(self) } } @@ -364,10 +364,10 @@ extension CarPlayNavigationViewController: StyleManagerDelegate { extension CarPlayNavigationViewController: RouteControllerDelegate { public func routeController(_ routeController: RouteController, didArriveAt waypoint: Waypoint) -> Bool { if routeController.routeProgress.isFinalLeg { - presentArrivalUI() - carPlayNavigationDelegate?.carPlayNavigationViewControllerDidArrive(self) + self.presentArrivalUI() + self.carPlayNavigationDelegate?.carPlayNavigationViewControllerDidArrive(self) } else { - presentWayointArrivalUI(for: waypoint) + self.presentWayointArrivalUI(for: waypoint) } return false } diff --git a/MapboxNavigation/DashedLineView.swift b/MapboxNavigation/DashedLineView.swift index 20593aa3..7821a69b 100644 --- a/MapboxNavigation/DashedLineView.swift +++ b/MapboxNavigation/DashedLineView.swift @@ -4,28 +4,28 @@ import UIKit @IBDesignable @objc(MBDashedLineView) public class DashedLineView: LineView { - @IBInspectable public var dashedLength: CGFloat = 4 { didSet { updateProperties() } } - @IBInspectable public var dashedGap: CGFloat = 4 { didSet { updateProperties() } } + @IBInspectable public var dashedLength: CGFloat = 4 { didSet { self.updateProperties() } } + @IBInspectable public var dashedGap: CGFloat = 4 { didSet { self.updateProperties() } } let dashedLineLayer = CAShapeLayer() override public func layoutSubviews() { - if dashedLineLayer.superlayer == nil { - layer.addSublayer(dashedLineLayer) + if self.dashedLineLayer.superlayer == nil { + layer.addSublayer(self.dashedLineLayer) } - updateProperties() + self.updateProperties() } func updateProperties() { let path = UIBezierPath() path.move(to: CGPoint(x: 0, y: bounds.height / 2)) path.addLine(to: CGPoint(x: bounds.width, y: bounds.height / 2)) - dashedLineLayer.path = path.cgPath + self.dashedLineLayer.path = path.cgPath - dashedLineLayer.frame = bounds - dashedLineLayer.fillColor = UIColor.clear.cgColor - dashedLineLayer.strokeColor = lineColor.cgColor - dashedLineLayer.lineWidth = bounds.height - dashedLineLayer.lineDashPattern = [dashedLength as NSNumber, dashedGap as NSNumber] + self.dashedLineLayer.frame = bounds + self.dashedLineLayer.fillColor = UIColor.clear.cgColor + self.dashedLineLayer.strokeColor = lineColor.cgColor + self.dashedLineLayer.lineWidth = bounds.height + self.dashedLineLayer.lineDashPattern = [self.dashedLength as NSNumber, self.dashedGap as NSNumber] } } diff --git a/MapboxNavigation/DataCache.swift b/MapboxNavigation/DataCache.swift index 28b29d8f..d8608f5a 100644 --- a/MapboxNavigation/DataCache.swift +++ b/MapboxNavigation/DataCache.swift @@ -6,8 +6,8 @@ public class DataCache: NSObject, BimodalDataCache { let fileCache = FileCache() override public init() { - memoryCache = NSCache() - memoryCache.name = "In-Memory Data Cache" + self.memoryCache = NSCache() + self.memoryCache.name = "In-Memory Data Cache" super.init() @@ -20,10 +20,10 @@ public class DataCache: NSObject, BimodalDataCache { Stores data in the cache for the given key. If `toDisk` is set to `true`, the completion handler is called following writing the data to disk, otherwise it is called immediately upon storing the data in the memory cache. */ public func store(_ data: Data, forKey key: String, toDisk: Bool, completion: CompletionHandler?) { - storeDataInMemoryCache(data, forKey: key) + self.storeDataInMemoryCache(data, forKey: key) if toDisk { - fileCache.store(data, forKey: key, completion: completion) + self.fileCache.store(data, forKey: key, completion: completion) } else { completion?() } @@ -42,7 +42,7 @@ public class DataCache: NSObject, BimodalDataCache { } if let data = fileCache.dataFromFileCache(forKey: key) { - storeDataInMemoryCache(data, forKey: key) + self.storeDataInMemoryCache(data, forKey: key) return data } @@ -53,18 +53,18 @@ public class DataCache: NSObject, BimodalDataCache { Clears out the memory cache. */ public func clearMemory() { - memoryCache.removeAllObjects() + self.memoryCache.removeAllObjects() } /* Clears the disk cache and calls the completion handler when finished. */ public func clearDisk(completion: CompletionHandler?) { - fileCache.clearDisk(completion: completion) + self.fileCache.clearDisk(completion: completion) } private func storeDataInMemoryCache(_ data: Data, forKey key: String) { - memoryCache.setObject(data as NSData, forKey: key as NSString) + self.memoryCache.setObject(data as NSData, forKey: key as NSString) } private func dataFromMemoryCache(forKey key: String) -> Data? { diff --git a/MapboxNavigation/DialogViewController.swift b/MapboxNavigation/DialogViewController.swift index 33a4e8f3..32a5600b 100644 --- a/MapboxNavigation/DialogViewController.swift +++ b/MapboxNavigation/DialogViewController.swift @@ -43,24 +43,24 @@ class DialogViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() - setupViews() - setupConstraints() + self.setupViews() + self.setupConstraints() } func setupViews() { - view.addGestureRecognizer(tapRecognizer) - view.addSubview(dialogView) - dialogView.addSubview(stackView) - stackView.addArrangedSubviews([imageView, label]) + view.addGestureRecognizer(self.tapRecognizer) + view.addSubview(self.dialogView) + self.dialogView.addSubview(self.stackView) + self.stackView.addArrangedSubviews([self.imageView, self.label]) } func setupConstraints() { - let dialogWidth = dialogView.widthAnchor.constraint(equalToConstant: Constants.dialogSize.width) - let dialogHeight = dialogView.heightAnchor.constraint(equalToConstant: Constants.dialogSize.height) - let dialogCenterX = dialogView.centerXAnchor.constraint(equalTo: view.centerXAnchor) - let dialogCenterY = dialogView.centerYAnchor.constraint(equalTo: view.centerYAnchor) - let stackCenterX = stackView.centerXAnchor.constraint(equalTo: dialogView.centerXAnchor) - let stackCenterY = stackView.centerYAnchor.constraint(equalTo: dialogView.centerYAnchor) + let dialogWidth = self.dialogView.widthAnchor.constraint(equalToConstant: Constants.dialogSize.width) + let dialogHeight = self.dialogView.heightAnchor.constraint(equalToConstant: Constants.dialogSize.height) + let dialogCenterX = self.dialogView.centerXAnchor.constraint(equalTo: view.centerXAnchor) + let dialogCenterY = self.dialogView.centerYAnchor.constraint(equalTo: view.centerYAnchor) + let stackCenterX = self.stackView.centerXAnchor.constraint(equalTo: self.dialogView.centerXAnchor) + let stackCenterY = self.stackView.centerYAnchor.constraint(equalTo: self.dialogView.centerYAnchor) let constraints = [dialogWidth, dialogHeight, dialogCenterX, dialogCenterY, @@ -78,11 +78,11 @@ class DialogViewController: UIViewController { override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) - perform(#selector(dismissAnimated), with: nil, afterDelay: 0.5) + perform(#selector(self.dismissAnimated), with: nil, afterDelay: 0.5) } @objc func dismissAnimated() { - NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(dismissAnimated), object: nil) + NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.dismissAnimated), object: nil) dismiss(animated: true, completion: nil) } } diff --git a/MapboxNavigation/EndOfRouteViewController.swift b/MapboxNavigation/EndOfRouteViewController.swift index 3b83619a..31b026dc 100644 --- a/MapboxNavigation/EndOfRouteViewController.swift +++ b/MapboxNavigation/EndOfRouteViewController.swift @@ -56,14 +56,14 @@ class EndOfRouteViewController: UIViewController { var comment: String? var rating: Int = 0 { didSet { - rating == 0 ? hideComments() : showComments() + self.rating == 0 ? self.hideComments() : self.showComments() } } open var destination: Waypoint? { didSet { guard isViewLoaded else { return } - updateInterface() + self.updateInterface() } } @@ -71,48 +71,48 @@ class EndOfRouteViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() - clearInterface() - stars.didChangeRating = { [weak self] new in self?.rating = new } - setPlaceholderText() - styleCommentView() - commentViewContainer.alpha = 0.0 // setting initial hidden state + self.clearInterface() + self.stars.didChangeRating = { [weak self] new in self?.rating = new } + self.setPlaceholderText() + self.styleCommentView() + self.commentViewContainer.alpha = 0.0 // setting initial hidden state } override func viewWillAppear(_ animated: Bool) { super.viewWillDisappear(animated) view.roundCorners([.topLeft, .topRight]) - preferredContentSize.height = height(for: .normal) - updateInterface() + preferredContentSize.height = self.height(for: .normal) + self.updateInterface() } // MARK: - IBActions @IBAction func endNavigationPressed(_ sender: Any) { - dismissView() + self.dismissView() } // MARK: - Private Functions private func styleCommentView() { - commentView.layer.cornerRadius = 6.0 - commentView.layer.borderColor = UIColor.lightGray.cgColor - commentView.layer.borderWidth = 1.0 - commentView.textContainerInset = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0) + self.commentView.layer.cornerRadius = 6.0 + self.commentView.layer.borderColor = UIColor.lightGray.cgColor + self.commentView.layer.borderWidth = 1.0 + self.commentView.textContainerInset = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0) } fileprivate func dismissView() { let dismissal: () -> Void = { self.dismissHandler?(self.rating, self.comment) } - guard commentView.isFirstResponder else { return _ = dismissal() } - commentView.resignFirstResponder() + guard self.commentView.isFirstResponder else { return _ = dismissal() } + self.commentView.resignFirstResponder() let fireTime = DispatchTime.now() + 0.3 // Not ideal, but works for now DispatchQueue.main.asyncAfter(deadline: fireTime, execute: dismissal) } private func showComments(animated: Bool = true) { - showCommentView.isActive = true - hideCommentView.isActive = false - ratingCommentsSpacing.constant = ConstraintSpacing.closer.rawValue - preferredContentSize.height = height(for: .commentShowing) + self.showCommentView.isActive = true + self.hideCommentView.isActive = false + self.ratingCommentsSpacing.constant = ConstraintSpacing.closer.rawValue + preferredContentSize.height = self.height(for: .commentShowing) let animate = { self.view.layoutIfNeeded() @@ -130,11 +130,11 @@ class EndOfRouteViewController: UIViewController { } private func hideComments(animated: Bool = true) { - labelContainer.isHidden = false - showCommentView.isActive = false - hideCommentView.isActive = true - ratingCommentsSpacing.constant = ConstraintSpacing.further.rawValue - preferredContentSize.height = height(for: .normal) + self.labelContainer.isHidden = false + self.showCommentView.isActive = false + self.hideCommentView.isActive = true + self.ratingCommentsSpacing.constant = ConstraintSpacing.further.rawValue + preferredContentSize.height = self.height(for: .normal) let animate = { self.view.layoutIfNeeded() @@ -156,22 +156,22 @@ class EndOfRouteViewController: UIViewController { } private func updateInterface() { - guard let name = destination?.name?.nonEmptyString else { return styleForUnnamedDestination() } - primary.text = name + guard let name = destination?.name?.nonEmptyString else { return self.styleForUnnamedDestination() } + self.primary.text = name } private func clearInterface() { - primary.text = nil - stars.rating = 0 + self.primary.text = nil + self.stars.rating = 0 } private func styleForUnnamedDestination() { - staticYouHaveArrived.alpha = 0.0 - primary.text = NSLocalizedString("END_OF_ROUTE_ARRIVED", bundle: .mapboxNavigation, value: "You have arrived", comment: "Title used for arrival") + self.staticYouHaveArrived.alpha = 0.0 + self.primary.text = NSLocalizedString("END_OF_ROUTE_ARRIVED", bundle: .mapboxNavigation, value: "You have arrived", comment: "Title used for arrival") } private func setPlaceholderText() { - commentView.text = placeholder + self.commentView.text = self.placeholder } } @@ -185,11 +185,11 @@ extension EndOfRouteViewController: UITextViewDelegate { } func textViewDidChange(_ textView: UITextView) { - comment = textView.text // Bind data model + self.comment = textView.text // Bind data model } func textViewDidBeginEditing(_ textView: UITextView) { - if textView.text == placeholder { + if textView.text == self.placeholder { textView.text = nil textView.alpha = 1.0 } @@ -198,7 +198,7 @@ extension EndOfRouteViewController: UITextViewDelegate { func textViewDidEndEditing(_ textView: UITextView) { if (textView.text?.isEmpty ?? true) == true { - textView.text = placeholder + textView.text = self.placeholder textView.alpha = 0.9 } } diff --git a/MapboxNavigation/ExitView.swift b/MapboxNavigation/ExitView.swift index 63703198..25bf8011 100644 --- a/MapboxNavigation/ExitView.swift +++ b/MapboxNavigation/ExitView.swift @@ -16,23 +16,23 @@ class ExitView: StylableView { @objc dynamic var foregroundColor: UIColor? { didSet { - layer.borderColor = foregroundColor?.cgColor - imageView.tintColor = foregroundColor - exitNumberLabel.textColor = foregroundColor + layer.borderColor = self.foregroundColor?.cgColor + self.imageView.tintColor = self.foregroundColor + self.exitNumberLabel.textColor = self.foregroundColor setNeedsDisplay() } } var side: ExitSide = .right { didSet { - populateExitImage() - rebuildConstraints() + self.populateExitImage() + self.rebuildConstraints() } } lazy var imageView: UIImageView = { let view = UIImageView(image: self.side.exitImage) - view.tintColor = foregroundColor + view.tintColor = self.foregroundColor view.translatesAutoresizingMaskIntoConstraints = false view.contentMode = .scaleAspectFit return view @@ -40,24 +40,24 @@ class ExitView: StylableView { lazy var exitNumberLabel: UILabel = { let label: UILabel = .forAutoLayout() - label.text = exitText + label.text = self.exitText label.textColor = .black - label.font = UIFont.boldSystemFont(ofSize: pointSize * ExitView.labelFontSizeScaleFactor) + label.font = UIFont.boldSystemFont(ofSize: self.pointSize * ExitView.labelFontSizeScaleFactor) return label }() var exitText: String? { didSet { - exitNumberLabel.text = exitText + self.exitNumberLabel.text = self.exitText invalidateIntrinsicContentSize() } } var pointSize: CGFloat { didSet { - exitNumberLabel.font = exitNumberLabel.font.withSize(pointSize * ExitView.labelFontSizeScaleFactor) - rebuildConstraints() + self.exitNumberLabel.font = self.exitNumberLabel.font.withSize(self.pointSize * ExitView.labelFontSizeScaleFactor) + self.rebuildConstraints() } } @@ -71,24 +71,24 @@ class ExitView: StylableView { self.init(frame: .zero) self.pointSize = pointSize self.side = side - exitText = text - commonInit() + self.exitText = text + self.commonInit() } override init(frame: CGRect) { - pointSize = 0.0 + self.pointSize = 0.0 super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { - pointSize = 0.0 + self.pointSize = 0.0 super.init(coder: aDecoder) - commonInit() + self.commonInit() } func rebuildConstraints() { NSLayoutConstraint.deactivate(constraints) - buildConstraints() + self.buildConstraints() } func commonInit() { @@ -96,8 +96,8 @@ class ExitView: StylableView { layer.masksToBounds = true // build view hierarchy - [imageView, exitNumberLabel].forEach(addSubview(_:)) - buildConstraints() + [self.imageView, self.exitNumberLabel].forEach(addSubview(_:)) + self.buildConstraints() setNeedsLayout() invalidateIntrinsicContentSize() @@ -105,19 +105,19 @@ class ExitView: StylableView { } func populateExitImage() { - imageView.image = side.exitImage + self.imageView.image = self.side.exitImage } func buildConstraints() { - let height = heightAnchor.constraint(equalToConstant: pointSize * 1.2) + let height = heightAnchor.constraint(equalToConstant: self.pointSize * 1.2) - let imageHeight = imageView.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.4) - let imageAspect = imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor, multiplier: imageView.image?.size.aspectRatio ?? 1.0) + let imageHeight = self.imageView.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.4) + let imageAspect = self.imageView.widthAnchor.constraint(equalTo: self.imageView.heightAnchor, multiplier: self.imageView.image?.size.aspectRatio ?? 1.0) - let imageCenterY = imageView.centerYAnchor.constraint(equalTo: centerYAnchor) - let labelCenterY = exitNumberLabel.centerYAnchor.constraint(equalTo: centerYAnchor) + let imageCenterY = self.imageView.centerYAnchor.constraint(equalTo: centerYAnchor) + let labelCenterY = self.exitNumberLabel.centerYAnchor.constraint(equalTo: centerYAnchor) - let sideConstraints = side != .left ? rightExitConstraints() : leftExitConstraints() + let sideConstraints = self.side != .left ? self.rightExitConstraints() : self.leftExitConstraints() let constraints = [height, imageHeight, imageAspect, imageCenterY, labelCenterY] + sideConstraints @@ -126,18 +126,18 @@ class ExitView: StylableView { } func rightExitConstraints() -> [NSLayoutConstraint] { - let labelLeading = exitNumberLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8) + let labelLeading = self.exitNumberLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8) let spacing = spacing(for: .right) - let imageLabelSpacing = exitNumberLabel.trailingAnchor.constraint(equalTo: imageView.leadingAnchor, constant: -1 * spacing) - let imageTrailing = trailingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 8) + let imageLabelSpacing = self.exitNumberLabel.trailingAnchor.constraint(equalTo: self.imageView.leadingAnchor, constant: -1 * spacing) + let imageTrailing = trailingAnchor.constraint(equalTo: self.imageView.trailingAnchor, constant: 8) return [labelLeading, imageLabelSpacing, imageTrailing] } func leftExitConstraints() -> [NSLayoutConstraint] { - let imageLeading = imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8) + let imageLeading = self.imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8) let spacing = spacing(for: .left) - let imageLabelSpacing = imageView.trailingAnchor.constraint(equalTo: exitNumberLabel.leadingAnchor, constant: -1 * spacing) - let labelTrailing = trailingAnchor.constraint(equalTo: exitNumberLabel.trailingAnchor, constant: 8) + let imageLabelSpacing = self.imageView.trailingAnchor.constraint(equalTo: self.exitNumberLabel.leadingAnchor, constant: -1 * spacing) + let labelTrailing = trailingAnchor.constraint(equalTo: self.exitNumberLabel.trailingAnchor, constant: 8) return [imageLeading, imageLabelSpacing, labelTrailing] } diff --git a/MapboxNavigation/FeedbackCollectionViewCell.swift b/MapboxNavigation/FeedbackCollectionViewCell.swift index e5b81d9e..15c631cb 100644 --- a/MapboxNavigation/FeedbackCollectionViewCell.swift +++ b/MapboxNavigation/FeedbackCollectionViewCell.swift @@ -25,23 +25,23 @@ class FeedbackCollectionViewCell: UICollectionViewCell { override init(frame: CGRect) { super.init(frame: frame) - commonInit() + self.commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) - commonInit() + self.commonInit() } func commonInit() { - setupViews() - setupConstraints() + self.setupViews() + self.setupConstraints() } override var isHighlighted: Bool { didSet { - if originalTransform == nil { - originalTransform = imageView.transform + if self.originalTransform == nil { + self.originalTransform = self.imageView.transform } UIView.defaultSpringAnimation(0.3, animations: { @@ -56,17 +56,17 @@ class FeedbackCollectionViewCell: UICollectionViewCell { } func setupViews() { - addSubview(imageView) - addSubview(titleLabel) + addSubview(self.imageView) + addSubview(self.titleLabel) } func setupConstraints() { - imageView.topAnchor.constraint(equalTo: topAnchor, constant: Constants.padding).isActive = true - imageView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true - imageView.heightAnchor.constraint(equalToConstant: Constants.imageSize.height).isActive = true - imageView.widthAnchor.constraint(equalToConstant: Constants.imageSize.width).isActive = true + self.imageView.topAnchor.constraint(equalTo: topAnchor, constant: Constants.padding).isActive = true + self.imageView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true + self.imageView.heightAnchor.constraint(equalToConstant: Constants.imageSize.height).isActive = true + self.imageView.widthAnchor.constraint(equalToConstant: Constants.imageSize.width).isActive = true - titleLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true - titleLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: Constants.padding).isActive = true + self.titleLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true + self.titleLabel.topAnchor.constraint(equalTo: self.imageView.bottomAnchor, constant: Constants.padding).isActive = true } } diff --git a/MapboxNavigation/GenericRouteShield.swift b/MapboxNavigation/GenericRouteShield.swift index 5881744b..7aa61299 100644 --- a/MapboxNavigation/GenericRouteShield.swift +++ b/MapboxNavigation/GenericRouteShield.swift @@ -10,8 +10,8 @@ public class GenericRouteShield: StylableView { // The color to use for the text and border. @objc dynamic var foregroundColor: UIColor? { didSet { - layer.borderColor = foregroundColor?.cgColor - routeLabel.textColor = foregroundColor + layer.borderColor = self.foregroundColor?.cgColor + self.routeLabel.textColor = self.foregroundColor setNeedsDisplay() } } @@ -19,9 +19,9 @@ public class GenericRouteShield: StylableView { // The label that contains the route code. lazy var routeLabel: UILabel = { let label: UILabel = .forAutoLayout() - label.text = routeText + label.text = self.routeText label.textColor = .black - label.font = UIFont.boldSystemFont(ofSize: pointSize * ExitView.labelFontSizeScaleFactor) + label.font = UIFont.boldSystemFont(ofSize: self.pointSize * ExitView.labelFontSizeScaleFactor) return label }() @@ -29,7 +29,7 @@ public class GenericRouteShield: StylableView { // The text to put in the label var routeText: String? { didSet { - routeLabel.text = routeText + self.routeLabel.text = self.routeText invalidateIntrinsicContentSize() } } @@ -37,32 +37,32 @@ public class GenericRouteShield: StylableView { // The size of the text the view attachment is contained within. var pointSize: CGFloat { didSet { - routeLabel.font = routeLabel.font.withSize(pointSize * ExitView.labelFontSizeScaleFactor) - rebuildConstraints() + self.routeLabel.font = self.routeLabel.font.withSize(self.pointSize * ExitView.labelFontSizeScaleFactor) + self.rebuildConstraints() } } convenience init(pointSize: CGFloat, text: String) { self.init(frame: .zero) self.pointSize = pointSize - routeText = text - commonInit() + self.routeText = text + self.commonInit() } override init(frame: CGRect) { - pointSize = 0.0 + self.pointSize = 0.0 super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { - pointSize = 0.0 + self.pointSize = 0.0 super.init(coder: aDecoder) - commonInit() + self.commonInit() } func rebuildConstraints() { NSLayoutConstraint.deactivate(constraints) - buildConstraints() + self.buildConstraints() } func commonInit() { @@ -70,8 +70,8 @@ public class GenericRouteShield: StylableView { layer.masksToBounds = true // build view hierarchy - addSubview(routeLabel) - buildConstraints() + addSubview(self.routeLabel) + self.buildConstraints() setNeedsLayout() invalidateIntrinsicContentSize() @@ -79,12 +79,12 @@ public class GenericRouteShield: StylableView { } func buildConstraints() { - let height = heightAnchor.constraint(equalToConstant: pointSize * 1.2) + let height = heightAnchor.constraint(equalToConstant: self.pointSize * 1.2) - let labelCenterY = routeLabel.centerYAnchor.constraint(equalTo: centerYAnchor) + let labelCenterY = self.routeLabel.centerYAnchor.constraint(equalTo: centerYAnchor) - let labelLeading = routeLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8) - let labelTrailingSpacing = routeLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8) + let labelLeading = self.routeLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8) + let labelTrailingSpacing = self.routeLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8) let constraints = [height, labelCenterY, labelLeading, labelTrailingSpacing] diff --git a/MapboxNavigation/HighwayShield.swift b/MapboxNavigation/HighwayShield.swift index 2966bcae..f418f213 100644 --- a/MapboxNavigation/HighwayShield.swift +++ b/MapboxNavigation/HighwayShield.swift @@ -82,35 +82,35 @@ enum HighwayShield { private static func type(for identifier: String) -> RoadTypeForLocaleRoadClassClosure? { switch identifier { case "motorway": - localeOnlyTransform(RoadType.motorway) + self.localeOnlyTransform(RoadType.motorway) case "expressway": - localeOnlyTransform(RoadType.expressway) + self.localeOnlyTransform(RoadType.expressway) case "national": - localeOnlyTransform(RoadType.national) + self.localeOnlyTransform(RoadType.national) case "federal": - localeOnlyTransform(RoadType.federal) + self.localeOnlyTransform(RoadType.federal) case "main": - localeOnlyTransform(RoadType.main) + self.localeOnlyTransform(RoadType.main) case "road": - localeOnlyTransform(RoadType.road) + self.localeOnlyTransform(RoadType.road) case "primary": - localeOnlyTransform(RoadType.primary) + self.localeOnlyTransform(RoadType.primary) case "secondary": - localeOnlyTransform(RoadType.secondary) + self.localeOnlyTransform(RoadType.secondary) case "trunk": - localeOnlyTransform(RoadType.trunk) + self.localeOnlyTransform(RoadType.trunk) case "regional": - localeOnlyTransform(RoadType.regional) + self.localeOnlyTransform(RoadType.regional) case "voivodeship": - localeOnlyTransform(RoadType.voivodeship) + self.localeOnlyTransform(RoadType.voivodeship) case "county": - localeOnlyTransform(RoadType.county) + self.localeOnlyTransform(RoadType.county) case "communal": - localeOnlyTransform(RoadType.communal) + self.localeOnlyTransform(RoadType.communal) case "provincial": - localeOnlyTransform(RoadType.provincial) + self.localeOnlyTransform(RoadType.provincial) case "metropolitan": - localeOnlyTransform(RoadType.metropolitan) + self.localeOnlyTransform(RoadType.metropolitan) case "state": RoadType.state case "highway": diff --git a/MapboxNavigation/ImageCache.swift b/MapboxNavigation/ImageCache.swift index db0306db..50afd514 100644 --- a/MapboxNavigation/ImageCache.swift +++ b/MapboxNavigation/ImageCache.swift @@ -5,10 +5,10 @@ class ImageCache: BimodalImageCache { let fileCache: FileCache init() { - memoryCache = NSCache() - memoryCache.name = "In-Memory Image Cache" + self.memoryCache = NSCache() + self.memoryCache.name = "In-Memory Image Cache" - fileCache = FileCache() + self.fileCache = FileCache() NotificationCenter.default.addObserver(self, selector: #selector(DataCache.clearMemory), name: UIApplication.didReceiveMemoryWarningNotification, object: nil) } @@ -19,14 +19,14 @@ class ImageCache: BimodalImageCache { Stores an image in the cache for the given key. If `toDisk` is set to `true`, the completion handler is called following writing the image to disk, otherwise it is called immediately upon storing the image in the memory cache. */ public func store(_ image: UIImage, forKey key: String, toDisk: Bool, completion: CompletionHandler?) { - storeImageInMemoryCache(image, forKey: key) + self.storeImageInMemoryCache(image, forKey: key) guard toDisk == true, let data = image.pngData() else { completion?() return } - fileCache.store(data, forKey: key, completion: completion) + self.fileCache.store(data, forKey: key, completion: completion) } /* @@ -42,7 +42,7 @@ class ImageCache: BimodalImageCache { } if let image = imageFromDiskCache(forKey: key) { - storeImageInMemoryCache(image, forKey: key) + self.storeImageInMemoryCache(image, forKey: key) return image } @@ -53,14 +53,14 @@ class ImageCache: BimodalImageCache { Clears out the memory cache. */ public func clearMemory() { - memoryCache.removeAllObjects() + self.memoryCache.removeAllObjects() } /* Clears the disk cache and calls the completion handler when finished. */ public func clearDisk(completion: CompletionHandler?) { - fileCache.clearDisk(completion: completion) + self.fileCache.clearDisk(completion: completion) } private func cost(forImage image: UIImage) -> Int { @@ -70,11 +70,11 @@ class ImageCache: BimodalImageCache { } private func storeImageInMemoryCache(_ image: UIImage, forKey key: String) { - memoryCache.setObject(image, forKey: key as NSString, cost: cost(forImage: image)) + self.memoryCache.setObject(image, forKey: key as NSString, cost: self.cost(forImage: image)) } private func imageFromMemoryCache(forKey key: String) -> UIImage? { - memoryCache.object(forKey: key as NSString) + self.memoryCache.object(forKey: key as NSString) } private func imageFromDiskCache(forKey key: String?) -> UIImage? { diff --git a/MapboxNavigation/ImageDownload.swift b/MapboxNavigation/ImageDownload.swift index 40c20bf3..015ace1c 100644 --- a/MapboxNavigation/ImageDownload.swift +++ b/MapboxNavigation/ImageDownload.swift @@ -18,11 +18,11 @@ class ImageDownloadOperation: Operation, ImageDownload { } override var isFinished: Bool { - _finished + self._finished } override var isExecuting: Bool { - _executing + self._executing } private var _finished = false { @@ -57,7 +57,7 @@ class ImageDownloadOperation: Operation, ImageDownload { } func addCompletion(_ completion: @escaping ImageDownloadCompletionBlock) { - barrierQueue.async(flags: .barrier) { + self.barrierQueue.async(flags: .barrier) { self.completionBlocks.append(completion) } } @@ -71,19 +71,19 @@ class ImageDownloadOperation: Operation, ImageDownload { if let dataTask { dataTask.cancel() - incomingData = nil + self.incomingData = nil self.dataTask = nil } - if isExecuting { - _executing = false + if self.isExecuting { + self._executing = false } - if !isFinished { - _finished = true + if !self.isFinished { + self._finished = true } - barrierQueue.async { + self.barrierQueue.async { self.completionBlocks.removeAll() } } @@ -95,13 +95,13 @@ class ImageDownloadOperation: Operation, ImageDownload { } if isCancelled == true { - _finished = true + self._finished = true return } - dataTask = session.dataTask(with: request) + dataTask = self.session.dataTask(with: self.request) if let dataTask { - _executing = true + self._executing = true dataTask.resume() } else { // fail and bail; connection failed or bad URL (client-side error) @@ -116,10 +116,10 @@ class ImageDownloadOperation: Operation, ImageDownload { return } if response.statusCode < 400 { - incomingData = Data() + self.incomingData = Data() completionHandler(.allow) } else { - fireAllCompletions(nil, data: nil, error: DownloadError.serverError) + self.fireAllCompletions(nil, data: nil, error: DownloadError.serverError) completionHandler(.cancel) } } @@ -128,32 +128,32 @@ class ImageDownloadOperation: Operation, ImageDownload { if var localData: Data = incomingData { let bytes = [UInt8](data) localData.append(bytes, count: bytes.count) - incomingData = localData + self.incomingData = localData } } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { guard error == nil else { - fireAllCompletions(nil, data: nil, error: DownloadError.clientError) + self.fireAllCompletions(nil, data: nil, error: DownloadError.clientError) return } if let data = incomingData, let image = UIImage(data: data, scale: UIScreen.main.scale) { - fireAllCompletions(image, data: data, error: nil) + self.fireAllCompletions(image, data: data, error: nil) } else { - fireAllCompletions(nil, data: incomingData, error: DownloadError.noImageData) + self.fireAllCompletions(nil, data: self.incomingData, error: DownloadError.noImageData) } - _finished = true - _executing = false - dataTask = nil - barrierQueue.async { + self._finished = true + self._executing = false + self.dataTask = nil + self.barrierQueue.async { self.completionBlocks.removeAll() } } private func fireAllCompletions(_ image: UIImage?, data: Data?, error: Error?) { - barrierQueue.sync { - completionBlocks.forEach { $0(image, data, error) } + self.barrierQueue.sync { + self.completionBlocks.forEach { $0(image, data, error) } } } } diff --git a/MapboxNavigation/ImageDownloader.swift b/MapboxNavigation/ImageDownloader.swift index 335fc3a1..2989795f 100644 --- a/MapboxNavigation/ImageDownloader.swift +++ b/MapboxNavigation/ImageDownloader.swift @@ -22,9 +22,9 @@ class ImageDownloader: NSObject, ReentrantImageDownloader, URLSessionDataDelegat private var headers: [String: String] = ["Accept": "image/*;q=0.8"] override init() { - downloadQueue = OperationQueue() - downloadQueue.name = Bundle.mapboxNavigation.bundleIdentifier! + ".ImageDownloader" - accessQueue = DispatchQueue(label: Bundle.mapboxNavigation.bundleIdentifier! + ".ImageDownloaderInternal", attributes: .concurrent) + self.downloadQueue = OperationQueue() + self.downloadQueue.name = Bundle.mapboxNavigation.bundleIdentifier! + ".ImageDownloader" + self.accessQueue = DispatchQueue(label: Bundle.mapboxNavigation.bundleIdentifier! + ".ImageDownloaderInternal", attributes: .concurrent) } convenience init(sessionConfiguration: URLSessionConfiguration? = nil, operationType: ImageDownload.Type? = nil) { @@ -44,7 +44,7 @@ class ImageDownloader: NSObject, ReentrantImageDownloader, URLSessionDataDelegat } func downloadImage(with url: URL, completion: ImageDownloadCompletionBlock?) { - accessQueue.sync(flags: .barrier) { + self.accessQueue.sync(flags: .barrier) { let request: URLRequest = self.urlRequest(with: url) var operation: ImageDownload if let activeOperation = self.activeOperation(with: url) { @@ -74,7 +74,7 @@ class ImageDownloader: NSObject, ReentrantImageDownloader, URLSessionDataDelegat private func urlRequest(with url: URL) -> URLRequest { var request = URLRequest(url: url) - request.allHTTPHeaderFields = headers + request.allHTTPHeaderFields = self.headers request.cachePolicy = .reloadIgnoringCacheData return request } @@ -109,7 +109,7 @@ class ImageDownloader: NSObject, ReentrantImageDownloader, URLSessionDataDelegat return } operation.urlSession?(session, task: task, didCompleteWithError: error) - accessQueue.async { + self.accessQueue.async { self.operations[url] = nil } } diff --git a/MapboxNavigation/ImageRepository.swift b/MapboxNavigation/ImageRepository.swift index 27f56743..d80d64a8 100644 --- a/MapboxNavigation/ImageRepository.swift +++ b/MapboxNavigation/ImageRepository.swift @@ -3,7 +3,7 @@ import UIKit class ImageRepository { public var sessionConfiguration: URLSessionConfiguration = .default { didSet { - imageDownloader = ImageDownloader(sessionConfiguration: sessionConfiguration) + self.imageDownloader = ImageDownloader(sessionConfiguration: self.sessionConfiguration) } } @@ -15,22 +15,22 @@ class ImageRepository { var useDiskCache: Bool required init(withDownloader downloader: ReentrantImageDownloader = ImageDownloader(), cache: BimodalImageCache = ImageCache(), useDisk: Bool = true) { - imageDownloader = downloader - imageCache = cache - useDiskCache = useDisk + self.imageDownloader = downloader + self.imageCache = cache + self.useDiskCache = useDisk } func resetImageCache(_ completion: CompletionHandler?) { - imageCache.clearMemory() - imageCache.clearDisk(completion: completion) + self.imageCache.clearMemory() + self.imageCache.clearDisk(completion: completion) } func storeImage(_ image: UIImage, forKey key: String, toDisk: Bool = true) { - imageCache.store(image, forKey: key, toDisk: toDisk, completion: nil) + self.imageCache.store(image, forKey: key, toDisk: toDisk, completion: nil) } func cachedImageForKey(_ key: String) -> UIImage? { - imageCache.image(forKey: key) + self.imageCache.image(forKey: key) } func imageWithURL(_ imageURL: URL, cacheKey: String, completion: @escaping (UIImage?) -> Void) { @@ -39,7 +39,7 @@ class ImageRepository { return } - _ = imageDownloader.downloadImage(with: imageURL, completion: { [weak self] image, _, error in + _ = self.imageDownloader.downloadImage(with: imageURL, completion: { [weak self] image, _, error in guard let strongSelf = self, let image else { completion(nil) return @@ -57,6 +57,6 @@ class ImageRepository { } func disableDiskCache() { - useDiskCache = false + self.useDiskCache = false } } diff --git a/MapboxNavigation/InstructionLabel.swift b/MapboxNavigation/InstructionLabel.swift index 77f51279..f0b23adf 100644 --- a/MapboxNavigation/InstructionLabel.swift +++ b/MapboxNavigation/InstructionLabel.swift @@ -18,7 +18,7 @@ open class InstructionLabel: StylableLabel, InstructionPresenterDataSource { didSet { guard let instruction else { text = nil - instructionPresenter = nil + self.instructionPresenter = nil return } let update: InstructionPresenter.ShieldDownloadCompletion = { [weak self] attributedText in @@ -29,8 +29,8 @@ open class InstructionLabel: StylableLabel, InstructionPresenterDataSource { let presenter = InstructionPresenter(instruction, dataSource: self, imageRepository: imageRepository, downloadCompletion: update) let attributed = presenter.attributedText() - attributedText = instructionDelegate?.label?(self, willPresent: instruction, as: attributed) ?? attributed - instructionPresenter = presenter + attributedText = self.instructionDelegate?.label?(self, willPresent: instruction, as: attributed) ?? attributed + self.instructionPresenter = presenter } } diff --git a/MapboxNavigation/InstructionPresenter.swift b/MapboxNavigation/InstructionPresenter.swift index 6f695769..c50b8ba8 100644 --- a/MapboxNavigation/InstructionPresenter.swift +++ b/MapboxNavigation/InstructionPresenter.swift @@ -18,7 +18,7 @@ class InstructionPresenter { self.instruction = instruction self.dataSource = dataSource self.imageRepository = imageRepository - onShieldDownload = downloadCompletion + self.onShieldDownload = downloadCompletion } typealias ImageDownloadCompletion = (UIImage?) -> Void @@ -30,7 +30,7 @@ class InstructionPresenter { func attributedText() -> NSAttributedString { let string = NSMutableAttributedString() - fittedAttributedComponents().forEach { string.append($0) } + self.fittedAttributedComponents().forEach { string.append($0) } return string } @@ -52,7 +52,7 @@ class InstructionPresenter { guard component.component.type == .text else { continue } guard let abbreviation = component.component.abbreviation else { continue } - attributedPairs.attributedStrings[component.index] = NSAttributedString(string: joinChar + abbreviation, attributes: attributes(for: source)) + attributedPairs.attributedStrings[component.index] = NSAttributedString(string: joinChar + abbreviation, attributes: self.attributes(for: source)) let newWidth: CGFloat = attributedPairs.attributedStrings.map { $0.size() }.reduce(.zero, +).width if newWidth <= availableBounds.width { @@ -133,7 +133,7 @@ class InstructionPresenter { func attributedString(forGenericShield component: VisualInstructionComponent, dataSource: DataSource) -> NSAttributedString? { guard component.type == .image, let text = component.text else { return nil } - return genericShield(text: text, component: component, dataSource: dataSource) + return self.genericShield(text: text, component: component, dataSource: dataSource) } func attributedString(forShieldComponent shield: VisualInstructionComponent, repository: ImageRepository, dataSource: DataSource, onImageDownload: @escaping ImageDownloadCompletion) -> NSAttributedString? { @@ -141,11 +141,11 @@ class InstructionPresenter { // If we have the shield already cached, use that. if let cachedImage = repository.cachedImageForKey(shieldKey) { - return attributedString(withFont: dataSource.font, shieldImage: cachedImage) + return self.attributedString(withFont: dataSource.font, shieldImage: cachedImage) } // Let's download the shield - shieldImageForComponent(shield, in: repository, height: dataSource.shieldHeight, completion: onImageDownload) + self.shieldImageForComponent(shield, in: repository, height: dataSource.shieldHeight, completion: onImageDownload) // Return nothing in the meantime, triggering downstream behavior (generic shield or text) return nil @@ -153,7 +153,7 @@ class InstructionPresenter { func attributedString(forTextComponent component: VisualInstructionComponent, dataSource: DataSource) -> NSAttributedString? { guard let text = component.text else { return nil } - return NSAttributedString(string: text, attributes: attributes(for: dataSource)) + return NSAttributedString(string: text, attributes: self.attributes(for: dataSource)) } private func shieldImageForComponent(_ component: VisualInstructionComponent, in repository: ImageRepository, height: CGFloat, completion: @escaping ImageDownloadCompletion) { @@ -165,7 +165,7 @@ class InstructionPresenter { } private func instructionHasDownloadedAllShields() -> Bool { - let textComponents = instruction.components.compactMap { $0 as? VisualInstructionComponent } + let textComponents = self.instruction.components.compactMap { $0 as? VisualInstructionComponent } guard !textComponents.isEmpty else { return false } for component in textComponents { @@ -173,7 +173,7 @@ class InstructionPresenter { continue } - if imageRepository.cachedImageForKey(key) == nil { + if self.imageRepository.cachedImageForKey(key) == nil { return false } } @@ -203,7 +203,7 @@ class InstructionPresenter { } else { let view = GenericRouteShield(pointSize: dataSource.font.pointSize, text: text) guard let image = takeSnapshot(on: view) else { return nil } - imageRepository.storeImage(image, forKey: key, toDisk: false) + self.imageRepository.storeImage(image, forKey: key, toDisk: false) attachment.image = image } @@ -224,7 +224,7 @@ class InstructionPresenter { } else { let view = ExitView(pointSize: dataSource.font.pointSize, side: side, text: text) guard let image = takeSnapshot(on: view) else { return nil } - imageRepository.storeImage(image, forKey: key, toDisk: false) + self.imageRepository.storeImage(image, forKey: key, toDisk: false) attachment.image = image } @@ -295,7 +295,7 @@ class RoadNameLabelAttachment: TextInstruction { self.text = text self.color = color self.scale = scale - self.image = compositeImage ?? image + self.image = self.compositeImage ?? image } } diff --git a/MapboxNavigation/InstructionsBannerView.swift b/MapboxNavigation/InstructionsBannerView.swift index fe649aab..59f4cb5d 100644 --- a/MapboxNavigation/InstructionsBannerView.swift +++ b/MapboxNavigation/InstructionsBannerView.swift @@ -38,14 +38,14 @@ open class BaseInstructionsBannerView: UIControl { weak var stepListIndicatorView: StepListIndicatorView! public weak var delegate: InstructionsBannerViewDelegate? { didSet { - stepListIndicatorView.isHidden = false + self.stepListIndicatorView.isHidden = false } } weak var instructionDelegate: VisualInstructionDelegate? { didSet { - primaryLabel.instructionDelegate = instructionDelegate - secondaryLabel.instructionDelegate = instructionDelegate + self.primaryLabel.instructionDelegate = self.instructionDelegate + self.secondaryLabel.instructionDelegate = self.instructionDelegate } } @@ -56,24 +56,24 @@ open class BaseInstructionsBannerView: UIControl { var distance: CLLocationDistance? { didSet { - distanceLabel.attributedDistanceString = nil + self.distanceLabel.attributedDistanceString = nil if let distance { - distanceLabel.attributedDistanceString = distanceFormatter.attributedString(for: distance) + self.distanceLabel.attributedDistanceString = self.distanceFormatter.attributedString(for: distance) } else { - distanceLabel.text = nil + self.distanceLabel.text = nil } } } override init(frame: CGRect) { super.init(frame: frame) - commonInit() + self.commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) - commonInit() + self.commonInit() } func commonInit() { @@ -81,19 +81,19 @@ open class BaseInstructionsBannerView: UIControl { setupLayout() centerYAlignInstructions() setupAvailableBounds() - stepListIndicatorView.isHidden = true + self.stepListIndicatorView.isHidden = true } @objc func draggedInstructionsBanner(_ sender: Any) { if let gestureRecognizer = sender as? UIPanGestureRecognizer, gestureRecognizer.state == .ended, let delegate { - stepListIndicatorView.isHidden = !stepListIndicatorView.isHidden + self.stepListIndicatorView.isHidden = !self.stepListIndicatorView.isHidden delegate.didDragInstructionsBanner?(self) } } @objc func tappedInstructionsBanner(_ sender: Any) { if let delegate { - stepListIndicatorView.isHidden = !stepListIndicatorView.isHidden + self.stepListIndicatorView.isHidden = !self.stepListIndicatorView.isHidden delegate.didTapInstructionsBanner?(self) } } @@ -104,7 +104,7 @@ open class BaseInstructionsBannerView: UIControl { @objc(updateForVisualInstructionBanner:) public func update(for instruction: VisualInstructionBanner?) { let secondaryInstruction = instruction?.secondaryInstruction - primaryLabel.numberOfLines = secondaryInstruction == nil ? 2 : 1 + self.primaryLabel.numberOfLines = secondaryInstruction == nil ? 2 : 1 if secondaryInstruction == nil { centerYAlignInstructions() @@ -112,20 +112,20 @@ open class BaseInstructionsBannerView: UIControl { baselineAlignInstructions() } - primaryLabel.instruction = instruction?.primaryInstruction - maneuverView.visualInstruction = instruction?.primaryInstruction - maneuverView.drivingSide = instruction?.drivingSide ?? .right - secondaryLabel.instruction = secondaryInstruction + self.primaryLabel.instruction = instruction?.primaryInstruction + self.maneuverView.visualInstruction = instruction?.primaryInstruction + self.maneuverView.drivingSide = instruction?.drivingSide ?? .right + self.secondaryLabel.instruction = secondaryInstruction } override open func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() - maneuverView.isStart = true + self.maneuverView.isStart = true let component = VisualInstructionComponent(type: .text, text: "Primary text label", imageURL: nil, abbreviation: nil, abbreviationPriority: NSNotFound) let instruction = VisualInstruction(text: nil, maneuverType: .none, maneuverDirection: .none, components: [component]) - primaryLabel.instruction = instruction + self.primaryLabel.instruction = instruction - distance = 100 + self.distance = 100 } /** @@ -133,6 +133,6 @@ open class BaseInstructionsBannerView: UIControl { */ public func updateDistance(for currentStepProgress: RouteStepProgress) { let distanceRemaining = currentStepProgress.distanceRemaining - distance = distanceRemaining > 5 ? distanceRemaining : 0 + self.distance = distanceRemaining > 5 ? distanceRemaining : 0 } } diff --git a/MapboxNavigation/LaneView.swift b/MapboxNavigation/LaneView.swift index 64f4bec1..55783c47 100644 --- a/MapboxNavigation/LaneView.swift +++ b/MapboxNavigation/LaneView.swift @@ -29,7 +29,7 @@ open class LaneView: UIView { } var appropriatePrimaryColor: UIColor { - isValid ? primaryColor : secondaryColor + self.isValid ? self.primaryColor : self.secondaryColor } static let defaultFrame: CGRect = .init(origin: .zero, size: 30.0) @@ -37,9 +37,9 @@ open class LaneView: UIView { convenience init(component: LaneIndicationComponent) { self.init(frame: LaneView.defaultFrame) backgroundColor = .clear - lane = Lane(indications: component.indications) - maneuverDirection = ManeuverDirection(description: component.indications.description) - isValid = component.isUsable + self.lane = Lane(indications: component.indications) + self.maneuverDirection = ManeuverDirection(description: component.indications.description) + self.isValid = component.isUsable } override open func draw(_ rect: CGRect) { @@ -48,119 +48,119 @@ open class LaneView: UIView { var flipLane: Bool if lane.indications.isSuperset(of: [.straightAhead, .sharpRight]) || lane.indications.isSuperset(of: [.straightAhead, .right]) || lane.indications.isSuperset(of: [.straightAhead, .slightRight]) { flipLane = false - if !isValid { + if !self.isValid { if lane.indications == .slightRight { - LanesStyleKit.drawLane_slight_right(primaryColor: appropriatePrimaryColor) + LanesStyleKit.drawLane_slight_right(primaryColor: self.appropriatePrimaryColor) } else { - LanesStyleKit.drawLane_straight_right(primaryColor: appropriatePrimaryColor) + LanesStyleKit.drawLane_straight_right(primaryColor: self.appropriatePrimaryColor) } - alpha = invalidAlpha - } else if maneuverDirection == .straightAhead { - LanesStyleKit.drawLane_straight_only(primaryColor: appropriatePrimaryColor, secondaryColor: secondaryColor) - } else if maneuverDirection == .sharpLeft || maneuverDirection == .left || maneuverDirection == .slightLeft { + alpha = self.invalidAlpha + } else if self.maneuverDirection == .straightAhead { + LanesStyleKit.drawLane_straight_only(primaryColor: self.appropriatePrimaryColor, secondaryColor: self.secondaryColor) + } else if self.maneuverDirection == .sharpLeft || self.maneuverDirection == .left || self.maneuverDirection == .slightLeft { if lane.indications == .slightLeft { - LanesStyleKit.drawLane_slight_right(primaryColor: appropriatePrimaryColor) + LanesStyleKit.drawLane_slight_right(primaryColor: self.appropriatePrimaryColor) } else { - LanesStyleKit.drawLane_right_h(primaryColor: appropriatePrimaryColor) + LanesStyleKit.drawLane_right_h(primaryColor: self.appropriatePrimaryColor) } flipLane = true } else { - LanesStyleKit.drawLane_right_only(primaryColor: appropriatePrimaryColor, secondaryColor: secondaryColor) + LanesStyleKit.drawLane_right_only(primaryColor: self.appropriatePrimaryColor, secondaryColor: self.secondaryColor) } } else if lane.indications.isSuperset(of: [.straightAhead, .sharpLeft]) || lane.indications.isSuperset(of: [.straightAhead, .left]) || lane.indications.isSuperset(of: [.straightAhead, .slightLeft]) { flipLane = true - if !isValid { + if !self.isValid { if lane.indications == .slightLeft { - LanesStyleKit.drawLane_slight_right(primaryColor: appropriatePrimaryColor) + LanesStyleKit.drawLane_slight_right(primaryColor: self.appropriatePrimaryColor) } else { - LanesStyleKit.drawLane_straight_right(primaryColor: appropriatePrimaryColor) + LanesStyleKit.drawLane_straight_right(primaryColor: self.appropriatePrimaryColor) } - alpha = invalidAlpha - } else if maneuverDirection == .straightAhead { - LanesStyleKit.drawLane_straight_only(primaryColor: appropriatePrimaryColor, secondaryColor: secondaryColor) - } else if maneuverDirection == .sharpRight || maneuverDirection == .right { - LanesStyleKit.drawLane_right_h(primaryColor: appropriatePrimaryColor) + alpha = self.invalidAlpha + } else if self.maneuverDirection == .straightAhead { + LanesStyleKit.drawLane_straight_only(primaryColor: self.appropriatePrimaryColor, secondaryColor: self.secondaryColor) + } else if self.maneuverDirection == .sharpRight || self.maneuverDirection == .right { + LanesStyleKit.drawLane_right_h(primaryColor: self.appropriatePrimaryColor) flipLane = false - } else if maneuverDirection == .slightRight { - LanesStyleKit.drawLane_slight_right(primaryColor: appropriatePrimaryColor) + } else if self.maneuverDirection == .slightRight { + LanesStyleKit.drawLane_slight_right(primaryColor: self.appropriatePrimaryColor) flipLane = false } else { - LanesStyleKit.drawLane_right_only(primaryColor: appropriatePrimaryColor, secondaryColor: secondaryColor) + LanesStyleKit.drawLane_right_only(primaryColor: self.appropriatePrimaryColor, secondaryColor: self.secondaryColor) } } else if lane.indications.description.components(separatedBy: ",").count >= 2 { // Hack: // Account for a configuation where there is no straight lane // but there are at least 2 indications. // In this situation, just draw a left/right arrow - if maneuverDirection == .sharpRight || maneuverDirection == .right { - LanesStyleKit.drawLane_right_h(primaryColor: appropriatePrimaryColor) + if self.maneuverDirection == .sharpRight || self.maneuverDirection == .right { + LanesStyleKit.drawLane_right_h(primaryColor: self.appropriatePrimaryColor) flipLane = false - } else if maneuverDirection == .slightRight { - LanesStyleKit.drawLane_slight_right(primaryColor: appropriatePrimaryColor) + } else if self.maneuverDirection == .slightRight { + LanesStyleKit.drawLane_slight_right(primaryColor: self.appropriatePrimaryColor) flipLane = false } else { - LanesStyleKit.drawLane_right_h(primaryColor: appropriatePrimaryColor) + LanesStyleKit.drawLane_right_h(primaryColor: self.appropriatePrimaryColor) flipLane = true } - alpha = isValid ? 1 : invalidAlpha + alpha = self.isValid ? 1 : self.invalidAlpha } else if lane.indications.isSuperset(of: [.sharpRight]) || lane.indications.isSuperset(of: [.right]) || lane.indications.isSuperset(of: [.slightRight]) { if lane.indications == .slightRight { - LanesStyleKit.drawLane_slight_right(primaryColor: appropriatePrimaryColor) + LanesStyleKit.drawLane_slight_right(primaryColor: self.appropriatePrimaryColor) } else { - LanesStyleKit.drawLane_right_h(primaryColor: appropriatePrimaryColor) + LanesStyleKit.drawLane_right_h(primaryColor: self.appropriatePrimaryColor) } flipLane = false - alpha = isValid ? 1 : invalidAlpha + alpha = self.isValid ? 1 : self.invalidAlpha } else if lane.indications.isSuperset(of: [.sharpLeft]) || lane.indications.isSuperset(of: [.left]) || lane.indications.isSuperset(of: [.slightLeft]) { if lane.indications == .slightLeft { - LanesStyleKit.drawLane_slight_right(primaryColor: appropriatePrimaryColor) + LanesStyleKit.drawLane_slight_right(primaryColor: self.appropriatePrimaryColor) } else { - LanesStyleKit.drawLane_right_h(primaryColor: appropriatePrimaryColor) + LanesStyleKit.drawLane_right_h(primaryColor: self.appropriatePrimaryColor) } flipLane = true - alpha = isValid ? 1 : invalidAlpha + alpha = self.isValid ? 1 : self.invalidAlpha } else if lane.indications.isSuperset(of: [.straightAhead]) { - LanesStyleKit.drawLane_straight(primaryColor: appropriatePrimaryColor) + LanesStyleKit.drawLane_straight(primaryColor: self.appropriatePrimaryColor) flipLane = false - alpha = isValid ? 1 : invalidAlpha + alpha = self.isValid ? 1 : self.invalidAlpha } else if lane.indications.isSuperset(of: [.uTurn]) { - LanesStyleKit.drawLane_uturn(primaryColor: appropriatePrimaryColor) + LanesStyleKit.drawLane_uturn(primaryColor: self.appropriatePrimaryColor) flipLane = false - alpha = isValid ? 1 : invalidAlpha - } else if lane.indications.isEmpty, isValid { + alpha = self.isValid ? 1 : self.invalidAlpha + } else if lane.indications.isEmpty, self.isValid { // If the lane indication is `none` and the maneuver modifier has a turn in it, // show the turn in the lane image. - if maneuverDirection == .sharpRight || maneuverDirection == .right || maneuverDirection == .slightRight { - if maneuverDirection == .slightRight { - LanesStyleKit.drawLane_slight_right(primaryColor: appropriatePrimaryColor) + if self.maneuverDirection == .sharpRight || self.maneuverDirection == .right || self.maneuverDirection == .slightRight { + if self.maneuverDirection == .slightRight { + LanesStyleKit.drawLane_slight_right(primaryColor: self.appropriatePrimaryColor) } else { - LanesStyleKit.drawLane_right_h(primaryColor: appropriatePrimaryColor) + LanesStyleKit.drawLane_right_h(primaryColor: self.appropriatePrimaryColor) } flipLane = false - } else if maneuverDirection == .sharpLeft || maneuverDirection == .left || maneuverDirection == .slightLeft { - if maneuverDirection == .slightLeft { - LanesStyleKit.drawLane_slight_right(primaryColor: appropriatePrimaryColor) + } else if self.maneuverDirection == .sharpLeft || self.maneuverDirection == .left || self.maneuverDirection == .slightLeft { + if self.maneuverDirection == .slightLeft { + LanesStyleKit.drawLane_slight_right(primaryColor: self.appropriatePrimaryColor) } else { - LanesStyleKit.drawLane_right_h(primaryColor: appropriatePrimaryColor) + LanesStyleKit.drawLane_right_h(primaryColor: self.appropriatePrimaryColor) } flipLane = true } else { - LanesStyleKit.drawLane_straight(primaryColor: appropriatePrimaryColor) + LanesStyleKit.drawLane_straight(primaryColor: self.appropriatePrimaryColor) flipLane = false } } else { - LanesStyleKit.drawLane_straight(primaryColor: appropriatePrimaryColor) + LanesStyleKit.drawLane_straight(primaryColor: self.appropriatePrimaryColor) flipLane = false - alpha = isValid ? 1 : invalidAlpha + alpha = self.isValid ? 1 : self.invalidAlpha } transform = CGAffineTransform(scaleX: flipLane ? -1 : 1, y: 1) } #if TARGET_INTERFACE_BUILDER - isValid = true - LanesStyleKit.drawLane_right_only(primaryColor: appropriatePrimaryColor, secondaryColor: secondaryColor) + self.isValid = true + LanesStyleKit.drawLane_right_only(primaryColor: self.appropriatePrimaryColor, secondaryColor: self.secondaryColor) #endif } } diff --git a/MapboxNavigation/LanesView.swift b/MapboxNavigation/LanesView.swift index d1f7fdc2..38fb2b5a 100644 --- a/MapboxNavigation/LanesView.swift +++ b/MapboxNavigation/LanesView.swift @@ -11,20 +11,20 @@ open class LanesView: UIView { override init(frame: CGRect) { super.init(frame: frame) - commonInit() + self.commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) - commonInit() + self.commonInit() } override open func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() for _ in 0 ... 4 { - let laneView = laneArrowView() - stackView.addArrangedSubview(laneView) + let laneView = self.laneArrowView() + self.stackView.addArrangedSubview(laneView) } } @@ -71,24 +71,24 @@ open class LanesView: UIView { */ @objc(updateForVisualInstructionBanner:) public func update(for visualInstruction: VisualInstructionBanner?) { - clearLaneViews() + self.clearLaneViews() guard let tertiaryInstruction = visualInstruction?.tertiaryInstruction, tertiaryInstruction.containsLaneIndications else { - hide() + self.hide() return } let laneIndications: [LaneIndicationComponent]? = tertiaryInstruction.components.compactMap { $0 as? LaneIndicationComponent } guard let lanes = laneIndications, !lanes.isEmpty else { - hide() + self.hide() return } let subviews = lanes.map { LaneView(component: $0) } - stackView.addArrangedSubviews(subviews) - show() + self.stackView.addArrangedSubviews(subviews) + self.show() } public func show(animated: Bool = true) { @@ -110,8 +110,8 @@ open class LanesView: UIView { } fileprivate func clearLaneViews() { - for arrangedSubview in stackView.arrangedSubviews { - stackView.removeArrangedSubview(arrangedSubview) + for arrangedSubview in self.stackView.arrangedSubviews { + self.stackView.removeArrangedSubview(arrangedSubview) arrangedSubview.removeFromSuperview() } } diff --git a/MapboxNavigation/MLNMapView.swift b/MapboxNavigation/MLNMapView.swift index 03d7de32..755e79c7 100644 --- a/MapboxNavigation/MLNMapView.swift +++ b/MapboxNavigation/MLNMapView.swift @@ -32,7 +32,7 @@ extension MLNMapView { return false } - let incidentsSourceIdentifiers = sourceIdentifiers(forTileSetIdentifier: tileSetIdentifier) + let incidentsSourceIdentifiers = self.sourceIdentifiers(forTileSetIdentifier: tileSetIdentifier) for layer in style.layers { if let layer = layer as? MLNVectorStyleLayer, let sourceIdentifier = layer.sourceIdentifier { if incidentsSourceIdentifiers.contains(sourceIdentifier), layer.sourceLayerIdentifier == layerIdentifier { @@ -54,7 +54,7 @@ extension MLNMapView { return } - let incidentsSourceIdentifiers = sourceIdentifiers(forTileSetIdentifier: tileSetIdentifier) + let incidentsSourceIdentifiers = self.sourceIdentifiers(forTileSetIdentifier: tileSetIdentifier) for layer in style.layers { if let layer = layer as? MLNVectorStyleLayer, let sourceIdentifier = layer.sourceIdentifier { if incidentsSourceIdentifiers.contains(sourceIdentifier), layer.sourceLayerIdentifier == layerIdentifier { @@ -69,10 +69,10 @@ extension MLNMapView { */ public var showsTraffic: Bool { get { - showsTileSet(withIdentifier: "mapbox.mapbox-traffic-v1", layerIdentifier: "traffic") + self.showsTileSet(withIdentifier: "mapbox.mapbox-traffic-v1", layerIdentifier: "traffic") } set { - setShowsTileSet(newValue, withIdentifier: "mapbox.mapbox-traffic-v1", layerIdentifier: "traffic") + self.setShowsTileSet(newValue, withIdentifier: "mapbox.mapbox-traffic-v1", layerIdentifier: "traffic") } } @@ -81,10 +81,10 @@ extension MLNMapView { */ public var showsIncidents: Bool { get { - showsTileSet(withIdentifier: "mapbox.mapbox-incidents-v1", layerIdentifier: "closures") + self.showsTileSet(withIdentifier: "mapbox.mapbox-incidents-v1", layerIdentifier: "closures") } set { - setShowsTileSet(newValue, withIdentifier: "mapbox.mapbox-incidents-v1", layerIdentifier: "closures") + self.setShowsTileSet(newValue, withIdentifier: "mapbox.mapbox-incidents-v1", layerIdentifier: "closures") } } } diff --git a/MapboxNavigation/ManeuverView.swift b/MapboxNavigation/ManeuverView.swift index 03842150..878c3546 100644 --- a/MapboxNavigation/ManeuverView.swift +++ b/MapboxNavigation/ManeuverView.swift @@ -63,15 +63,15 @@ open class ManeuverView: UIView { let resizing: ManeuversStyleKit.ResizingBehavior = .aspectFit #if TARGET_INTERFACE_BUILDER - ManeuversStyleKit.drawFork(frame: bounds, resizing: resizing, primaryColor: primaryColor, secondaryColor: secondaryColor) + ManeuversStyleKit.drawFork(frame: bounds, resizing: resizing, primaryColor: self.primaryColor, secondaryColor: self.secondaryColor) return #endif guard let visualInstruction else { - if isStart { - ManeuversStyleKit.drawStarting(frame: bounds, resizing: resizing, primaryColor: primaryColor) - } else if isEnd { - ManeuversStyleKit.drawDestination(frame: bounds, resizing: resizing, primaryColor: primaryColor) + if self.isStart { + ManeuversStyleKit.drawStarting(frame: bounds, resizing: resizing, primaryColor: self.primaryColor) + } else if self.isEnd { + ManeuversStyleKit.drawDestination(frame: bounds, resizing: resizing, primaryColor: self.primaryColor) } return } @@ -85,53 +85,53 @@ open class ManeuverView: UIView { switch type { case .merge: - ManeuversStyleKit.drawMerge(frame: bounds, resizing: resizing, primaryColor: primaryColor, secondaryColor: secondaryColor) + ManeuversStyleKit.drawMerge(frame: bounds, resizing: resizing, primaryColor: self.primaryColor, secondaryColor: self.secondaryColor) flip = [.left, .slightLeft, .sharpLeft].contains(direction) case .takeOffRamp: - ManeuversStyleKit.drawOfframp(frame: bounds, resizing: resizing, primaryColor: primaryColor, secondaryColor: secondaryColor) + ManeuversStyleKit.drawOfframp(frame: bounds, resizing: resizing, primaryColor: self.primaryColor, secondaryColor: self.secondaryColor) flip = [.left, .slightLeft, .sharpLeft].contains(direction) case .reachFork: - ManeuversStyleKit.drawFork(frame: bounds, resizing: resizing, primaryColor: primaryColor, secondaryColor: secondaryColor) + ManeuversStyleKit.drawFork(frame: bounds, resizing: resizing, primaryColor: self.primaryColor, secondaryColor: self.secondaryColor) flip = [.left, .slightLeft, .sharpLeft].contains(direction) case .takeRoundabout, .turnAtRoundabout, .takeRotary: - ManeuversStyleKit.drawRoundabout(frame: bounds, resizing: resizing, primaryColor: primaryColor, secondaryColor: secondaryColor, roundabout_angle: CGFloat(visualInstruction.finalHeading)) - flip = drivingSide == .left + ManeuversStyleKit.drawRoundabout(frame: bounds, resizing: resizing, primaryColor: self.primaryColor, secondaryColor: self.secondaryColor, roundabout_angle: CGFloat(visualInstruction.finalHeading)) + flip = self.drivingSide == .left case .arrive: switch direction { case .right: - ManeuversStyleKit.drawArriveright(frame: bounds, resizing: resizing, primaryColor: primaryColor) + ManeuversStyleKit.drawArriveright(frame: bounds, resizing: resizing, primaryColor: self.primaryColor) case .left: - ManeuversStyleKit.drawArriveright(frame: bounds, resizing: resizing, primaryColor: primaryColor) + ManeuversStyleKit.drawArriveright(frame: bounds, resizing: resizing, primaryColor: self.primaryColor) flip = true default: - ManeuversStyleKit.drawArrive(frame: bounds, resizing: resizing, primaryColor: primaryColor) + ManeuversStyleKit.drawArrive(frame: bounds, resizing: resizing, primaryColor: self.primaryColor) } default: switch direction { case .right: - ManeuversStyleKit.drawArrowright(frame: bounds, resizing: resizing, primaryColor: primaryColor) + ManeuversStyleKit.drawArrowright(frame: bounds, resizing: resizing, primaryColor: self.primaryColor) flip = false case .slightRight: - ManeuversStyleKit.drawArrowslightright(frame: bounds, resizing: resizing, primaryColor: primaryColor) + ManeuversStyleKit.drawArrowslightright(frame: bounds, resizing: resizing, primaryColor: self.primaryColor) flip = false case .sharpRight: - ManeuversStyleKit.drawArrowsharpright(frame: bounds, resizing: resizing, primaryColor: primaryColor) + ManeuversStyleKit.drawArrowsharpright(frame: bounds, resizing: resizing, primaryColor: self.primaryColor) flip = false case .left: - ManeuversStyleKit.drawArrowright(frame: bounds, resizing: resizing, primaryColor: primaryColor) + ManeuversStyleKit.drawArrowright(frame: bounds, resizing: resizing, primaryColor: self.primaryColor) flip = true case .slightLeft: - ManeuversStyleKit.drawArrowslightright(frame: bounds, resizing: resizing, primaryColor: primaryColor) + ManeuversStyleKit.drawArrowslightright(frame: bounds, resizing: resizing, primaryColor: self.primaryColor) flip = true case .sharpLeft: - ManeuversStyleKit.drawArrowsharpright(frame: bounds, resizing: resizing, primaryColor: primaryColor) + ManeuversStyleKit.drawArrowsharpright(frame: bounds, resizing: resizing, primaryColor: self.primaryColor) flip = true case .uTurn: - ManeuversStyleKit.drawArrow180right(frame: bounds, resizing: resizing, primaryColor: primaryColor) - flip = drivingSide == .left + ManeuversStyleKit.drawArrow180right(frame: bounds, resizing: resizing, primaryColor: self.primaryColor) + flip = self.drivingSide == .left default: - ManeuversStyleKit.drawArrowstraight(frame: bounds, resizing: resizing, primaryColor: primaryColor) + ManeuversStyleKit.drawArrowstraight(frame: bounds, resizing: resizing, primaryColor: self.primaryColor) } } diff --git a/MapboxNavigation/NavigationMapView.swift b/MapboxNavigation/NavigationMapView.swift index 43c395b0..8efbd9c3 100644 --- a/MapboxNavigation/NavigationMapView.swift +++ b/MapboxNavigation/NavigationMapView.swift @@ -91,33 +91,33 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { var shouldPositionCourseViewFrameByFrame = false { didSet { - if shouldPositionCourseViewFrameByFrame { + if self.shouldPositionCourseViewFrameByFrame { preferredFramesPerSecond = FrameIntervalOptions.defaultFramesPerSecond } } } var showsRoute: Bool { - style?.layer(withIdentifier: routeLayerIdentifier) != nil + style?.layer(withIdentifier: self.routeLayerIdentifier) != nil } override open var showsUserLocation: Bool { get { - if tracksUserCourse || userLocationForCourseTracking != nil { - return !(userCourseView?.isHidden ?? true) + if self.tracksUserCourse || self.userLocationForCourseTracking != nil { + return !(self.userCourseView?.isHidden ?? true) } return super.showsUserLocation } set { - if tracksUserCourse || userLocationForCourseTracking != nil { + if self.tracksUserCourse || self.userLocationForCourseTracking != nil { super.showsUserLocation = false - if userCourseView == nil { - userCourseView = UserPuckCourseView(frame: CGRect(origin: .zero, size: CGSize(width: 75, height: 75))) + if self.userCourseView == nil { + self.userCourseView = UserPuckCourseView(frame: CGRect(origin: .zero, size: CGSize(width: 75, height: 75))) } - userCourseView?.isHidden = !newValue + self.userCourseView?.isHidden = !newValue } else { - userCourseView?.isHidden = true + self.userCourseView?.isHidden = true super.showsUserLocation = newValue } } @@ -133,8 +133,8 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { } let contentFrame = bounds.inset(by: safeArea) - let courseViewWidth = userCourseView?.frame.width ?? 0 - let courseViewHeight = userCourseView?.frame.height ?? 0 + let courseViewWidth = self.userCourseView?.frame.width ?? 0 + let courseViewHeight = self.userCourseView?.frame.height ?? 0 let edgePadding = UIEdgeInsets(top: 50 + courseViewHeight / 2, left: 50 + courseViewWidth / 2, bottom: 50 + courseViewHeight / 2, @@ -154,16 +154,16 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { */ open var tracksUserCourse: Bool = false { didSet { - if tracksUserCourse { - enableFrameByFrameCourseViewTracking(for: 3) - altitude = defaultAltitude - showsUserLocation = true - courseTrackingDelegate?.navigationMapViewDidStartTrackingCourse?(self) + if self.tracksUserCourse { + self.enableFrameByFrameCourseViewTracking(for: 3) + self.altitude = self.defaultAltitude + self.showsUserLocation = true + self.courseTrackingDelegate?.navigationMapViewDidStartTrackingCourse?(self) } else { - courseTrackingDelegate?.navigationMapViewDidStopTrackingCourse?(self) + self.courseTrackingDelegate?.navigationMapViewDidStopTrackingCourse?(self) } if let location = userLocationForCourseTracking { - updateCourseTracking(location: location, animated: true) + self.updateCourseTracking(location: location, animated: true) } } } @@ -178,9 +178,9 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { oldValue?.removeFromSuperview() if let userCourseView { if let location = userLocationForCourseTracking { - updateCourseTracking(location: location, animated: false) + self.updateCourseTracking(location: location, animated: false) } else { - userCourseView.center = userAnchorPoint + userCourseView.center = self.userAnchorPoint } addSubview(userCourseView) } @@ -192,21 +192,21 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { // MARK: - Initalizers override public init(frame: CGRect) { - altitude = defaultAltitude + self.altitude = self.defaultAltitude super.init(frame: frame) - commonInit() + self.commonInit() } public required init?(coder decoder: NSCoder) { - altitude = defaultAltitude + self.altitude = self.defaultAltitude super.init(coder: decoder) - commonInit() + self.commonInit() } override public init(frame: CGRect, styleURL: URL?) { - altitude = defaultAltitude + self.altitude = self.defaultAltitude super.init(frame: frame, styleURL: styleURL) - commonInit() + self.commonInit() } public convenience init(frame: CGRect, styleURL: URL?, config: MNConfig? = nil) { @@ -218,10 +218,10 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { } fileprivate func commonInit() { - makeGestureRecognizersRespectCourseTracking() - makeGestureRecognizersUpdateCourseView() + self.makeGestureRecognizersRespectCourseTracking() + self.makeGestureRecognizersUpdateCourseView() - resumeNotifications() + self.resumeNotifications() } deinit { @@ -245,14 +245,14 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { super.layoutSubviews() // If the map is in tracking mode, make sure we update the camera after the layout pass. - if tracksUserCourse { - updateCourseTracking(location: userLocationForCourseTracking, camera: camera, animated: false) + if self.tracksUserCourse { + self.updateCourseTracking(location: self.userLocationForCourseTracking, camera: camera, animated: false) } } override open func anchorPoint(forGesture gesture: UIGestureRecognizer) -> CGPoint { - if tracksUserCourse { - userAnchorPoint + if self.tracksUserCourse { + self.userAnchorPoint } else { super.anchorPoint(forGesture: gesture) } @@ -261,16 +261,16 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { override open func mapViewDidFinishRenderingFrameFullyRendered(_ fullyRendered: Bool) { super.mapViewDidFinishRenderingFrameFullyRendered(fullyRendered) - guard shouldPositionCourseViewFrameByFrame else { return } + guard self.shouldPositionCourseViewFrameByFrame else { return } guard let location = userLocationForCourseTracking else { return } - userCourseView?.center = convert(location.coordinate, toPointTo: self) + self.userCourseView?.center = convert(location.coordinate, toPointTo: self) } // MARK: - Notifications func resumeNotifications() { - NotificationCenter.default.addObserver(self, selector: #selector(progressDidChange(_:)), name: .routeControllerProgressDidChange, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(self.progressDidChange(_:)), name: .routeControllerProgressDidChange, object: nil) let gestures = gestureRecognizers ?? [] let mapTapGesture = mapTapGesture @@ -283,15 +283,15 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { } @objc func progressDidChange(_ notification: Notification) { - guard tracksUserCourse else { return } + guard self.tracksUserCourse else { return } let routeProgress = notification.userInfo![RouteControllerNotificationUserInfoKey.routeProgressKey] as! RouteProgress if let location = userLocationForCourseTracking { - let cameraUpdated = courseTrackingDelegate?.updateCamera?(self, location: location, routeProgress: routeProgress) ?? false + let cameraUpdated = self.courseTrackingDelegate?.updateCamera?(self, location: location, routeProgress: routeProgress) ?? false if !cameraUpdated { - let newCamera = MLNMapCamera(lookingAtCenter: location.coordinate, acrossDistance: altitude, pitch: 45, heading: location.course) + let newCamera = MLNMapCamera(lookingAtCenter: location.coordinate, acrossDistance: self.altitude, pitch: 45, heading: location.course) let function = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear) setCamera(newCamera, withDuration: 1, animationTimingFunction: function, edgePadding: UIEdgeInsets.zero, completionHandler: nil) } @@ -308,10 +308,10 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { if let upcomingStep = routeProgress.currentLegProgress.upComingStep, upcomingStep.maneuverDirection == .straightAhead || upcomingStep.maneuverDirection == .slightLeft || upcomingStep.maneuverDirection == .slightRight { - preferredFramesPerSecond = shouldPositionCourseViewFrameByFrame ? FrameIntervalOptions.defaultFramesPerSecond : FrameIntervalOptions.decreasedFramesPerSecond + preferredFramesPerSecond = self.shouldPositionCourseViewFrameByFrame ? FrameIntervalOptions.defaultFramesPerSecond : FrameIntervalOptions.decreasedFramesPerSecond } else if durationUntilNextManeuver > FrameIntervalOptions.durationUntilNextManeuver, durationSincePreviousManeuver > FrameIntervalOptions.durationSincePreviousManeuver { - preferredFramesPerSecond = shouldPositionCourseViewFrameByFrame ? FrameIntervalOptions.defaultFramesPerSecond : FrameIntervalOptions.decreasedFramesPerSecond + preferredFramesPerSecond = self.shouldPositionCourseViewFrameByFrame ? FrameIntervalOptions.defaultFramesPerSecond : FrameIntervalOptions.decreasedFramesPerSecond } else { preferredFramesPerSecond = FrameIntervalOptions.pluggedInFramesPerSecond } @@ -319,32 +319,32 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { // Track position on a frame by frame basis. Used for first location update and when resuming tracking mode func enableFrameByFrameCourseViewTracking(for duration: TimeInterval) { - NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(disableFrameByFramePositioning), object: nil) - perform(#selector(disableFrameByFramePositioning), with: nil, afterDelay: duration) - shouldPositionCourseViewFrameByFrame = true + NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.disableFrameByFramePositioning), object: nil) + perform(#selector(self.disableFrameByFramePositioning), with: nil, afterDelay: duration) + self.shouldPositionCourseViewFrameByFrame = true } // MARK: - User Tracking @objc fileprivate func disableFrameByFramePositioning() { - shouldPositionCourseViewFrameByFrame = false + self.shouldPositionCourseViewFrameByFrame = false } @objc private func disableUserCourseTracking() { - guard tracksUserCourse else { return } - tracksUserCourse = false + guard self.tracksUserCourse else { return } + self.tracksUserCourse = false } @objc public func updateCourseTracking(location: CLLocation?, camera: MLNMapCamera? = nil, animated: Bool = false) { // While animating to overhead mode, don't animate the puck. - let duration: TimeInterval = animated && !isAnimatingToOverheadMode ? 1 : 0 - animatesUserLocation = animated - userLocationForCourseTracking = location + let duration: TimeInterval = animated && !self.isAnimatingToOverheadMode ? 1 : 0 + self.animatesUserLocation = animated + self.userLocationForCourseTracking = location guard let location, CLLocationCoordinate2DIsValid(location.coordinate) else { return } - if !tracksUserCourse || userAnchorPoint != userCourseView?.center ?? userAnchorPoint { + if !self.tracksUserCourse || self.userAnchorPoint != userCourseView?.center ?? self.userAnchorPoint { UIView.animate(withDuration: duration, delay: 0, options: [.curveLinear, .beginFromCurrentState], animations: { self.userCourseView?.center = self.convert(location.coordinate, toPointTo: self) }) @@ -354,10 +354,10 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { if let customTransformation = userCourseView.update?(location: location, pitch: self.camera.pitch, direction: direction, animated: animated, tracksUserCourse: tracksUserCourse) { customTransformation } else { - self.userCourseView?.applyDefaultUserPuckTransformation(location: location, pitch: self.camera.pitch, direction: direction, animated: animated, tracksUserCourse: tracksUserCourse) + self.userCourseView?.applyDefaultUserPuckTransformation(location: location, pitch: self.camera.pitch, direction: direction, animated: animated, tracksUserCourse: self.tracksUserCourse) } } else { - userCourseView?.applyDefaultUserPuckTransformation(location: location, pitch: self.camera.pitch, direction: direction, animated: animated, tracksUserCourse: tracksUserCourse) + userCourseView?.applyDefaultUserPuckTransformation(location: location, pitch: self.camera.pitch, direction: direction, animated: animated, tracksUserCourse: self.tracksUserCourse) } } @@ -369,13 +369,13 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { @objc func didRecieveTap(sender: UITapGestureRecognizer) { guard let routes, let tapPoint = sender.point else { return } - let waypointTest = waypoints(on: routes, closeTo: tapPoint) // are there waypoints near the tapped location? + let waypointTest = self.waypoints(on: routes, closeTo: tapPoint) // are there waypoints near the tapped location? if let selected = waypointTest?.first { // test passes - navigationMapDelegate?.navigationMapView?(self, didSelect: selected) + self.navigationMapDelegate?.navigationMapView?(self, didSelect: selected) return } else if let routes = self.routes(closeTo: tapPoint) { guard let selectedRoute = routes.first else { return } - navigationMapDelegate?.navigationMapView?(self, didSelect: selectedRoute) + self.navigationMapDelegate?.navigationMapView?(self, didSelect: selectedRoute) } } @@ -383,8 +383,8 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { preferredFramesPerSecond = FrameIntervalOptions.defaultFramesPerSecond if sender.state == .ended { - altitude = camera.altitude - enableFrameByFrameCourseViewTracking(for: 2) + self.altitude = camera.altitude + self.enableFrameByFrameCourseViewTracking(for: 2) } // Capture altitude for double tap and two finger tap after animation finishes @@ -399,15 +399,15 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { let velocity = pan.velocity(in: self) let didFling = sqrt(velocity.x * velocity.x + velocity.y * velocity.y) > 100 if didFling { - enableFrameByFrameCourseViewTracking(for: 1) + self.enableFrameByFrameCourseViewTracking(for: 1) } } } if sender.state == .changed { guard let location = userLocationForCourseTracking else { return } - userCourseView?.layer.removeAllAnimations() - userCourseView?.center = convert(location.coordinate, toPointTo: self) + self.userCourseView?.layer.removeAllAnimations() + self.userCourseView?.center = convert(location.coordinate, toPointTo: self) } } @@ -423,14 +423,14 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { let coords = active.coordinates, !coords.isEmpty else { return } // empty array - removeArrow() - removeRoutes() - removeWaypoints() + self.removeArrow() + self.removeRoutes() + self.removeWaypoints() - showRoutes(routes) - showWaypoints(active) + self.showRoutes(routes) + self.showWaypoints(active) - fit(to: active, facing: 0, padding: padding, animated: animated) + self.fit(to: active, facing: 0, padding: padding, animated: animated) } func fit(to route: Route, facing direction: CLLocationDirection = 0, padding: UIEdgeInsets = NavigationMapView.defaultPadding, animated: Bool = false) { @@ -451,8 +451,8 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { guard let mainRoute = routes.first else { return } self.routes = routes - let polylines = navigationMapDelegate?.navigationMapView?(self, shapeFor: routes) ?? shape(for: routes, legIndex: legIndex) - let mainPolylineSimplified = navigationMapDelegate?.navigationMapView?(self, simplifiedShapeFor: mainRoute) ?? shape(forCasingOf: mainRoute, legIndex: legIndex) + let polylines = self.navigationMapDelegate?.navigationMapView?(self, shapeFor: routes) ?? self.shape(for: routes, legIndex: legIndex) + let mainPolylineSimplified = self.navigationMapDelegate?.navigationMapView?(self, simplifiedShapeFor: mainRoute) ?? self.shape(forCasingOf: mainRoute, legIndex: legIndex) if let source = style.source(withIdentifier: sourceIdentifier) as? MLNShapeSource, let sourceSimplified = style.source(withIdentifier: sourceCasingIdentifier) as? MLNShapeSource { @@ -464,12 +464,12 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { style.addSource(lineSource) style.addSource(lineCasingSource) - let line = navigationMapDelegate?.navigationMapView?(self, routeStyleLayerWithIdentifier: routeLayerIdentifier, source: lineSource) ?? routeStyleLayer(identifier: routeLayerIdentifier, source: lineSource) - let lineCasing = navigationMapDelegate?.navigationMapView?(self, routeCasingStyleLayerWithIdentifier: routeLayerCasingIdentifier, source: lineCasingSource) ?? routeCasingStyleLayer(identifier: routeLayerCasingIdentifier, source: lineSource) + let line = self.navigationMapDelegate?.navigationMapView?(self, routeStyleLayerWithIdentifier: self.routeLayerIdentifier, source: lineSource) ?? self.routeStyleLayer(identifier: self.routeLayerIdentifier, source: lineSource) + let lineCasing = self.navigationMapDelegate?.navigationMapView?(self, routeCasingStyleLayerWithIdentifier: self.routeLayerCasingIdentifier, source: lineCasingSource) ?? self.routeCasingStyleLayer(identifier: self.routeLayerCasingIdentifier, source: lineSource) for layer in style.layers.reversed() { if !(layer is MLNSymbolStyleLayer), - layer.identifier != arrowLayerIdentifier, layer.identifier != arrowSymbolLayerIdentifier, layer.identifier != arrowCasingSymbolLayerIdentifier, layer.identifier != arrowLayerStrokeIdentifier, layer.identifier != waypointCircleIdentifier { + layer.identifier != self.arrowLayerIdentifier, layer.identifier != self.arrowSymbolLayerIdentifier, layer.identifier != self.arrowCasingSymbolLayerIdentifier, layer.identifier != self.arrowLayerStrokeIdentifier, layer.identifier != self.waypointCircleIdentifier { style.insertLayer(line, below: layer) style.insertLayer(lineCasing, below: line) break @@ -513,17 +513,17 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { let waypoints: [Waypoint] = Array(route.legs.map(\.destination).dropLast()) - let source = navigationMapDelegate?.navigationMapView?(self, shapeFor: waypoints, legIndex: legIndex) ?? shape(for: waypoints, legIndex: legIndex) + let source = self.navigationMapDelegate?.navigationMapView?(self, shapeFor: waypoints, legIndex: legIndex) ?? self.shape(for: waypoints, legIndex: legIndex) if route.routeOptions.waypoints.count > 2 { // are we on a multipoint route? - routes = [route] // update the model + self.routes = [route] // update the model if let waypointSource = style.source(withIdentifier: waypointSourceIdentifier) as? MLNShapeSource { waypointSource.shape = source } else { let sourceShape = MLNShapeSource(identifier: waypointSourceIdentifier, shape: source, options: sourceOptions) style.addSource(sourceShape) - let circles = navigationMapDelegate?.navigationMapView?(self, waypointStyleLayerWithIdentifier: waypointCircleIdentifier, source: sourceShape) ?? routeWaypointCircleStyleLayer(identifier: waypointCircleIdentifier, source: sourceShape) - let symbols = navigationMapDelegate?.navigationMapView?(self, waypointSymbolStyleLayerWithIdentifier: waypointSymbolIdentifier, source: sourceShape) ?? routeWaypointSymbolStyleLayer(identifier: waypointSymbolIdentifier, source: sourceShape) + let circles = self.navigationMapDelegate?.navigationMapView?(self, waypointStyleLayerWithIdentifier: self.waypointCircleIdentifier, source: sourceShape) ?? self.routeWaypointCircleStyleLayer(identifier: self.waypointCircleIdentifier, source: sourceShape) + let symbols = self.navigationMapDelegate?.navigationMapView?(self, waypointSymbolStyleLayerWithIdentifier: self.waypointSymbolIdentifier, source: sourceShape) ?? self.routeWaypointSymbolStyleLayer(identifier: self.waypointSymbolIdentifier, source: sourceShape) if let arrowLayer = style.layer(withIdentifier: arrowCasingSymbolLayerIdentifier) { style.insertLayer(circles, below: arrowLayer) @@ -620,7 +620,7 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { curveType: .linear, parameters: nil, stops: NSExpression(forConstantValue: MLNRouteLineWidthByZoomLevel.multiplied(by: 0.7))) - arrow.lineColor = NSExpression(forConstantValue: maneuverArrowColor) + arrow.lineColor = NSExpression(forConstantValue: self.maneuverArrowColor) style.addSource(arrowSource) style.addLayer(arrow) @@ -636,7 +636,7 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { curveType: .linear, parameters: nil, stops: NSExpression(forConstantValue: MLNRouteLineWidthByZoomLevel.multiplied(by: 0.8))) - arrowStroke.lineColor = NSExpression(forConstantValue: maneuverArrowStrokeColor) + arrowStroke.lineColor = NSExpression(forConstantValue: self.maneuverArrowStrokeColor) style.addSource(arrowSourceStroke) style.insertLayer(arrowStroke, below: arrow) @@ -659,7 +659,7 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { let arrowSymbolLayer = MLNSymbolStyleLayer(identifier: arrowSymbolLayerIdentifier, source: arrowSymbolSource) arrowSymbolLayer.minimumZoomLevel = minimumZoomLevel arrowSymbolLayer.iconImageName = NSExpression(forConstantValue: "triangle-tip-navigation") - arrowSymbolLayer.iconColor = NSExpression(forConstantValue: maneuverArrowColor) + arrowSymbolLayer.iconColor = NSExpression(forConstantValue: self.maneuverArrowColor) arrowSymbolLayer.iconRotationAlignment = NSExpression(forConstantValue: "map") arrowSymbolLayer.iconRotation = NSExpression(forConstantValue: shaftDirection as NSNumber) arrowSymbolLayer.iconScale = NSExpression(forMLNInterpolating: .zoomLevelVariable, @@ -671,7 +671,7 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { let arrowSymbolLayerCasing = MLNSymbolStyleLayer(identifier: arrowCasingSymbolLayerIdentifier, source: arrowSymbolSource) arrowSymbolLayerCasing.minimumZoomLevel = arrowSymbolLayer.minimumZoomLevel arrowSymbolLayerCasing.iconImageName = arrowSymbolLayer.iconImageName - arrowSymbolLayerCasing.iconColor = NSExpression(forConstantValue: maneuverArrowStrokeColor) + arrowSymbolLayerCasing.iconColor = NSExpression(forConstantValue: self.maneuverArrowStrokeColor) arrowSymbolLayerCasing.iconRotationAlignment = arrowSymbolLayer.iconRotationAlignment arrowSymbolLayerCasing.iconRotation = arrowSymbolLayer.iconRotation arrowSymbolLayerCasing.iconScale = NSExpression(forMLNInterpolating: .zoomLevelVariable, @@ -736,7 +736,7 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { func makeGestureRecognizersUpdateCourseView() { for gestureRecognizer in gestureRecognizers ?? [] { - gestureRecognizer.addTarget(self, action: #selector(updateCourseView(_:))) + gestureRecognizer.addTarget(self, action: #selector(self.updateCourseView(_:))) } } @@ -757,7 +757,7 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { // lets filter to see which ones are under threshold let candidates = closest.filter { let coordinatePoint = self.convert($0.coordinate, toPointTo: self) - return coordinatePoint.distance(to: point) < tapGestureDistanceThreshold + return coordinatePoint.distance(to: point) < self.tapGestureDistanceThreshold } return candidates @@ -786,7 +786,7 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { let closestCoordinate = Polyline($0.coordinates!).closestCoordinate(to: tapCoordinate)!.coordinate let closestPoint = self.convert(closestCoordinate, toPointTo: self) - return closestPoint.distance(to: point) < tapGestureDistanceThreshold + return closestPoint.distance(to: point) < self.tapGestureDistanceThreshold } return candidates } @@ -826,7 +826,7 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { return index == 0 ? stepCoordinates : allCoordinates + stepCoordinates.suffix(from: 1) } - let mergedCongestionSegments = combine(legCoordinates, with: legCongestion) + let mergedCongestionSegments = self.combine(legCoordinates, with: legCongestion) let lines: [MLNPolylineFeature] = mergedCongestionSegments.map { (congestionSegment: CongestionSegment) -> MLNPolylineFeature in let polyline = MLNPolylineFeature(coordinates: congestionSegment.0, count: UInt(congestionSegment.0.count)) @@ -931,8 +931,8 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { stops: NSExpression(forConstantValue: MLNRouteLineWidthByZoomLevel)) line.lineColor = NSExpression( forConditional: NSPredicate(format: "isAlternateRoute == true"), - trueExpression: NSExpression(forConstantValue: routeLineAlternativeColor), - falseExpression: NSExpression(forConstantValue: routeLineColor)) + trueExpression: NSExpression(forConstantValue: self.routeLineAlternativeColor), + falseExpression: NSExpression(forConstantValue: self.routeLineColor)) line.lineOpacity = NSExpression( forConditional: NSPredicate(format: "isAlternateRoute == true"), @@ -956,8 +956,8 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { lineCasing.lineColor = NSExpression( forConditional: NSPredicate(format: "isAlternateRoute == true"), - trueExpression: NSExpression(forConstantValue: routeLineCasingAlternativeColor), - falseExpression: NSExpression(forConstantValue: routeLineCasingColor)) + trueExpression: NSExpression(forConstantValue: self.routeLineCasingAlternativeColor), + falseExpression: NSExpression(forConstantValue: self.routeLineCasingColor)) lineCasing.lineOpacity = NSExpression( forConditional: NSPredicate(format: "isAlternateRoute == true"), @@ -1067,11 +1067,11 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { Sets the camera directly over a series of coordinates. */ @objc public func setOverheadCameraView(from userLocation: CLLocationCoordinate2D, along coordinates: [CLLocationCoordinate2D], for bounds: UIEdgeInsets) { - isAnimatingToOverheadMode = true + self.isAnimatingToOverheadMode = true let slicedLine = Polyline(coordinates).sliced(from: userLocation).coordinates let line = MLNPolyline(coordinates: slicedLine, count: UInt(slicedLine.count)) - tracksUserCourse = false + self.tracksUserCourse = false // If the user has a short distance left on the route, prevent the camera from zooming all the way. // `MLNMapView.setVisibleCoordinateBounds(:edgePadding:animated:)` will go beyond what is convenient for the driver. @@ -1080,7 +1080,7 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { camera.pitch = 0 camera.heading = 0 camera.centerCoordinate = userLocation - camera.altitude = defaultAltitude + camera.altitude = self.defaultAltitude setCamera(camera, withDuration: 1, animationTimingFunction: nil) { [weak self] in self?.isAnimatingToOverheadMode = false } @@ -1101,8 +1101,8 @@ open class NavigationMapView: MLNMapView, UIGestureRecognizerDelegate { Recenters the camera and begins tracking the user's location. */ @objc public func recenterMap() { - tracksUserCourse = true - enableFrameByFrameCourseViewTracking(for: 3) + self.tracksUserCourse = true + self.enableFrameByFrameCourseViewTracking(for: 3) } } diff --git a/MapboxNavigation/NavigationView.swift b/MapboxNavigation/NavigationView.swift index 22e8d903..007839f9 100644 --- a/MapboxNavigation/NavigationView.swift +++ b/MapboxNavigation/NavigationView.swift @@ -74,9 +74,9 @@ open class NavigationView: UIView { lazy var mapView: NavigationMapView = { let map: NavigationMapView = .forAutoLayout(frame: self.bounds) - map.delegate = delegate - map.navigationMapDelegate = delegate - map.courseTrackingDelegate = delegate + map.delegate = self.delegate + map.navigationMapDelegate = self.delegate + map.courseTrackingDelegate = self.delegate map.showsUserLocation = true return map }() @@ -85,7 +85,7 @@ open class NavigationView: UIView { lazy var instructionsBannerView: InstructionsBannerView = { let banner: InstructionsBannerView = .forAutoLayout() - banner.delegate = delegate + banner.delegate = self.delegate return banner }() @@ -106,7 +106,7 @@ open class NavigationView: UIView { lazy var nextBannerView: NextBannerView = .forAutoLayout(hidden: true) lazy var statusView: StatusView = { let view: StatusView = .forAutoLayout() - view.delegate = delegate + view.delegate = self.delegate view.isHidden = true return view }() @@ -129,7 +129,7 @@ open class NavigationView: UIView { weak var delegate: NavigationViewDelegate? { didSet { - updateDelegates() + self.updateDelegates() } } @@ -141,7 +141,7 @@ open class NavigationView: UIView { oldValue?.removeFromSuperview() if let eor = endOfRouteView { addSubview(eor) } - endOfRouteView?.translatesAutoresizingMaskIntoConstraints = false + self.endOfRouteView?.translatesAutoresizingMaskIntoConstraints = false } } @@ -150,36 +150,36 @@ open class NavigationView: UIView { convenience init(delegate: NavigationViewDelegate) { self.init(frame: .zero) self.delegate = delegate - updateDelegates() // this needs to be called because didSet's do not fire in init contexts. + self.updateDelegates() // this needs to be called because didSet's do not fire in init contexts. } override init(frame: CGRect) { super.init(frame: frame) - commonInit() + self.commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) - commonInit() + self.commonInit() } func commonInit() { - setupViews() + self.setupViews() setupConstraints() } func setupStackViews() { - setupInformationStackView() - floatingStackView.addArrangedSubviews([overviewButton, muteButton, reportButton]) + self.setupInformationStackView() + self.floatingStackView.addArrangedSubviews([self.overviewButton, self.muteButton, self.reportButton]) } func setupInformationStackView() { let informationChildren: [UIView] = [instructionsBannerView, lanesView, nextBannerView, statusView] - informationStackView.addArrangedSubviews(informationChildren) + self.informationStackView.addArrangedSubviews(informationChildren) for informationChild in informationChildren { - informationChild.leadingAnchor.constraint(equalTo: informationStackView.leadingAnchor).isActive = true - informationChild.trailingAnchor.constraint(equalTo: informationStackView.trailingAnchor).isActive = true + informationChild.leadingAnchor.constraint(equalTo: self.informationStackView.leadingAnchor).isActive = true + informationChild.trailingAnchor.constraint(equalTo: self.informationStackView.trailingAnchor).isActive = true } } @@ -192,8 +192,8 @@ open class NavigationView: UIView { } func setupViews() { - setupStackViews() - setupContainers() + self.setupStackViews() + self.setupContainers() let subviews: [UIView] = [ mapView, @@ -211,22 +211,22 @@ open class NavigationView: UIView { override open func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() DayStyle().apply() - [mapView, instructionsBannerView, lanesView, bottomBannerView, nextBannerView].forEach { $0.prepareForInterfaceBuilder() } - wayNameView.text = "Street Label" + [self.mapView, self.instructionsBannerView, self.lanesView, self.bottomBannerView, self.nextBannerView].forEach { $0.prepareForInterfaceBuilder() } + self.wayNameView.text = "Street Label" } @objc func cancelButtonTapped(_ sender: CancelButton) { - delegate?.navigationView(self, didTapCancelButton: bottomBannerView.cancelButton) + self.delegate?.navigationView(self, didTapCancelButton: self.bottomBannerView.cancelButton) } private func updateDelegates() { - mapView.delegate = delegate - mapView.navigationMapDelegate = delegate - mapView.courseTrackingDelegate = delegate - instructionsBannerView.delegate = delegate - instructionsBannerView.instructionDelegate = delegate - nextBannerView.instructionDelegate = delegate - statusView.delegate = delegate + self.mapView.delegate = self.delegate + self.mapView.navigationMapDelegate = self.delegate + self.mapView.courseTrackingDelegate = self.delegate + self.instructionsBannerView.delegate = self.delegate + self.instructionsBannerView.instructionDelegate = self.delegate + self.nextBannerView.instructionDelegate = self.delegate + self.statusView.delegate = self.delegate } } diff --git a/MapboxNavigation/NavigationViewController.swift b/MapboxNavigation/NavigationViewController.swift index f944c4d3..7dc06535 100644 --- a/MapboxNavigation/NavigationViewController.swift +++ b/MapboxNavigation/NavigationViewController.swift @@ -199,14 +199,14 @@ open class NavigationViewController: UIViewController { */ @objc public var route: Route! { didSet { - if routeController == nil { - routeController = RouteController(along: route, directions: directions, locationManager: locationManager) - routeController.delegate = self + if self.routeController == nil { + self.routeController = RouteController(along: self.route, directions: self.directions, locationManager: self.locationManager) + self.routeController.delegate = self } else { - routeController.routeProgress = RouteProgress(route: route) + self.routeController.routeProgress = RouteProgress(route: self.route) } - NavigationSettings.shared.distanceUnit = route.routeOptions.locale.usesMetric ? .kilometer : .mile - mapViewController?.notifyDidReroute(route: route) + NavigationSettings.shared.distanceUnit = self.route.routeOptions.locale.usesMetric ? .kilometer : .mile + self.mapViewController?.notifyDidReroute(route: self.route) } } @@ -244,7 +244,7 @@ open class NavigationViewController: UIViewController { */ @objc public var routeController: RouteController! { didSet { - mapViewController?.routeController = routeController + self.mapViewController?.routeController = self.routeController } } @@ -254,7 +254,7 @@ open class NavigationViewController: UIViewController { - note: Do not change this map view’s delegate. */ @objc public var mapView: NavigationMapView? { - mapViewController?.mapView + self.mapViewController?.mapView } /** @@ -274,8 +274,8 @@ open class NavigationViewController: UIViewController { */ @objc public var showsReportFeedback: Bool = true { didSet { - mapViewController?.reportButton.isHidden = !showsReportFeedback - showsEndOfRouteFeedback = showsReportFeedback + self.mapViewController?.reportButton.isHidden = !self.showsReportFeedback + self.showsEndOfRouteFeedback = self.showsReportFeedback } } @@ -284,7 +284,7 @@ open class NavigationViewController: UIViewController { */ @objc public var showsEndOfRouteFeedback: Bool = true { didSet { - mapViewController?.showsEndOfRoute = showsEndOfRouteFeedback + self.mapViewController?.showsEndOfRoute = self.showsEndOfRouteFeedback } } @@ -293,7 +293,7 @@ open class NavigationViewController: UIViewController { */ @objc public var automaticallyAdjustsStyleForTimeOfDay = true { didSet { - styleManager.automaticallyAdjustsStyleForTimeOfDay = automaticallyAdjustsStyleForTimeOfDay + self.styleManager.automaticallyAdjustsStyleForTimeOfDay = self.automaticallyAdjustsStyleForTimeOfDay } } @@ -307,7 +307,7 @@ open class NavigationViewController: UIViewController { */ @objc public var isUsedInConjunctionWithCarPlayWindow = false { didSet { - mapViewController?.isUsedInConjunctionWithCarPlayWindow = isUsedInConjunctionWithCarPlayWindow + self.mapViewController?.isUsedInConjunctionWithCarPlayWindow = self.isUsedInConjunctionWithCarPlayWindow } } @@ -332,13 +332,13 @@ open class NavigationViewController: UIViewController { var currentStatusBarStyle: UIStatusBarStyle = .default { didSet { - mapViewController?.instructionsBannerView.backgroundColor = InstructionsBannerView.appearance().backgroundColor - mapViewController?.instructionsBannerContentView.backgroundColor = InstructionsBannerContentView.appearance().backgroundColor + self.mapViewController?.instructionsBannerView.backgroundColor = InstructionsBannerView.appearance().backgroundColor + self.mapViewController?.instructionsBannerContentView.backgroundColor = InstructionsBannerContentView.appearance().backgroundColor } } override open var preferredStatusBarStyle: UIStatusBarStyle { - currentStatusBarStyle + self.currentStatusBarStyle } public required init?(coder aDecoder: NSCoder) { @@ -384,10 +384,10 @@ open class NavigationViewController: UIViewController { view.addSubview(mapSubview) mapSubview.pinInSuperview() - mapViewController.reportButton.isHidden = !showsReportFeedback + mapViewController.reportButton.isHidden = !self.showsReportFeedback - styleManager = StyleManager(self) - styleManager.styles = styles ?? [DayStyle(), NightStyle()] + self.styleManager = StyleManager(self) + self.styleManager.styles = styles ?? [DayStyle(), NightStyle()] if !(route.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.") @@ -402,44 +402,44 @@ open class NavigationViewController: UIViewController { super.viewDidLoad() // 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 - resumeNotifications() + _ = self.voiceController + self.resumeNotifications() view.clipsToBounds = true } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) - if shouldManageApplicationIdleTimer { + if self.shouldManageApplicationIdleTimer { UIApplication.shared.isIdleTimerDisabled = true } - if routeController.locationManager is SimulatedLocationManager { + if self.routeController.locationManager is SimulatedLocationManager { let localized = String.Localized.simulationStatus(speed: 1) - mapViewController?.statusView.show(localized, showSpinner: false, interactive: true) + self.mapViewController?.statusView.show(localized, showSpinner: false, interactive: true) } } override open func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) - if shouldManageApplicationIdleTimer { + if self.shouldManageApplicationIdleTimer { UIApplication.shared.isIdleTimerDisabled = false } - routeController.suspendLocationUpdates() + self.routeController.suspendLocationUpdates() } // MARK: Route controller notifications func resumeNotifications() { - NotificationCenter.default.addObserver(self, selector: #selector(progressDidChange(notification:)), name: .routeControllerProgressDidChange, object: routeController) - NotificationCenter.default.addObserver(self, selector: #selector(didPassInstructionPoint(notification:)), name: .routeControllerDidPassSpokenInstructionPoint, object: routeController) + NotificationCenter.default.addObserver(self, selector: #selector(self.progressDidChange(notification:)), name: .routeControllerProgressDidChange, object: self.routeController) + NotificationCenter.default.addObserver(self, selector: #selector(self.didPassInstructionPoint(notification:)), name: .routeControllerDidPassSpokenInstructionPoint, object: self.routeController) } func suspendNotifications() { - NotificationCenter.default.removeObserver(self, name: .routeControllerProgressDidChange, object: routeController) - NotificationCenter.default.removeObserver(self, name: .routeControllerDidPassSpokenInstructionPoint, object: routeController) + NotificationCenter.default.removeObserver(self, name: .routeControllerProgressDidChange, object: self.routeController) + NotificationCenter.default.removeObserver(self, name: .routeControllerDidPassSpokenInstructionPoint, object: self.routeController) } @objc func progressDidChange(notification: NSNotification) { @@ -447,34 +447,34 @@ open class NavigationViewController: UIViewController { let location = notification.userInfo![RouteControllerNotificationUserInfoKey.locationKey] as! CLLocation let secondsRemaining = routeProgress.currentLegProgress.currentStepProgress.durationRemaining - mapViewController?.notifyDidChange(routeProgress: routeProgress, location: location, secondsRemaining: secondsRemaining) + self.mapViewController?.notifyDidChange(routeProgress: routeProgress, location: location, secondsRemaining: secondsRemaining) // If the user has arrived, don't snap the user puck. // In the case the user drives beyond the waypoint, // we should accurately depict this. - let shouldPreventReroutesWhenArrivingAtWaypoint = routeController.delegate?.routeController?(routeController, shouldPreventReroutesWhenArrivingAt: routeController.routeProgress.currentLeg.destination) ?? true - let userHasArrivedAndShouldPreventRerouting = shouldPreventReroutesWhenArrivingAtWaypoint && !routeController.routeProgress.currentLegProgress.userHasArrivedAtWaypoint + let shouldPreventReroutesWhenArrivingAtWaypoint = self.routeController.delegate?.routeController?(self.routeController, shouldPreventReroutesWhenArrivingAt: self.routeController.routeProgress.currentLeg.destination) ?? true + let userHasArrivedAndShouldPreventRerouting = shouldPreventReroutesWhenArrivingAtWaypoint && !self.routeController.routeProgress.currentLegProgress.userHasArrivedAtWaypoint - if snapsUserLocationAnnotationToRoute, + if self.snapsUserLocationAnnotationToRoute, userHasArrivedAndShouldPreventRerouting { - mapViewController?.mapView.updateCourseTracking(location: location, animated: true) + self.mapViewController?.mapView.updateCourseTracking(location: location, animated: true) } } @objc func didPassInstructionPoint(notification: NSNotification) { let routeProgress = notification.userInfo![RouteControllerNotificationUserInfoKey.routeProgressKey] as! RouteProgress - mapViewController?.updateCameraAltitude(for: routeProgress) + self.mapViewController?.updateCameraAltitude(for: routeProgress) - clearStaleNotifications() + self.clearStaleNotifications() if routeProgress.currentLegProgress.currentStepProgress.durationRemaining <= RouteControllerHighAlertInterval { - scheduleLocalNotification(about: routeProgress.currentLegProgress.currentStep, legIndex: routeProgress.legIndex, numberOfLegs: routeProgress.route.legs.count) + self.scheduleLocalNotification(about: routeProgress.currentLegProgress.currentStep, legIndex: routeProgress.legIndex, numberOfLegs: routeProgress.route.legs.count) } } func scheduleLocalNotification(about step: RouteStep, legIndex: Int?, numberOfLegs: Int?) { - guard sendsNotifications else { return } + guard self.sendsNotifications else { return } guard UIApplication.shared.applicationState == .background else { return } guard let text = step.instructionsSpokenAlongStep?.last?.text else { return } @@ -482,14 +482,14 @@ open class NavigationViewController: UIViewController { notification.alertBody = text notification.fireDate = Date() - clearStaleNotifications() + self.clearStaleNotifications() UIApplication.shared.cancelAllLocalNotifications() UIApplication.shared.scheduleLocalNotification(notification) } func clearStaleNotifications() { - guard sendsNotifications else { return } + guard self.sendsNotifications else { return } // Remove all outstanding notifications from notification center. // This will only work if it's set to 1 and then back to 0. // This way, there is always just one notification. @@ -540,47 +540,47 @@ open class NavigationViewController: UIViewController { extension NavigationViewController: RouteMapViewControllerDelegate { public func navigationMapView(_ mapView: NavigationMapView, routeCasingStyleLayerWithIdentifier identifier: String, source: MLNSource) -> MLNStyleLayer? { - delegate?.navigationViewController?(self, routeCasingStyleLayerWithIdentifier: identifier, source: source) + self.delegate?.navigationViewController?(self, routeCasingStyleLayerWithIdentifier: identifier, source: source) } public func navigationMapView(_ mapView: NavigationMapView, routeStyleLayerWithIdentifier identifier: String, source: MLNSource) -> MLNStyleLayer? { - delegate?.navigationViewController?(self, routeStyleLayerWithIdentifier: identifier, source: source) + self.delegate?.navigationViewController?(self, routeStyleLayerWithIdentifier: identifier, source: source) } public func navigationMapView(_ mapView: NavigationMapView, didSelect route: Route) { - delegate?.navigationViewController?(self, didSelect: route) + self.delegate?.navigationViewController?(self, didSelect: route) } @objc public func navigationMapView(_ mapView: NavigationMapView, shapeFor routes: [Route]) -> MLNShape? { - delegate?.navigationViewController?(self, shapeFor: routes) + self.delegate?.navigationViewController?(self, shapeFor: routes) } @objc public func navigationMapView(_ mapView: NavigationMapView, simplifiedShapeFor route: Route) -> MLNShape? { - delegate?.navigationViewController?(self, simplifiedShapeFor: route) + self.delegate?.navigationViewController?(self, simplifiedShapeFor: route) } public func navigationMapView(_ mapView: NavigationMapView, waypointStyleLayerWithIdentifier identifier: String, source: MLNSource) -> MLNStyleLayer? { - delegate?.navigationViewController?(self, waypointStyleLayerWithIdentifier: identifier, source: source) + self.delegate?.navigationViewController?(self, waypointStyleLayerWithIdentifier: identifier, source: source) } public func navigationMapView(_ mapView: NavigationMapView, waypointSymbolStyleLayerWithIdentifier identifier: String, source: MLNSource) -> MLNStyleLayer? { - delegate?.navigationViewController?(self, waypointSymbolStyleLayerWithIdentifier: identifier, source: source) + self.delegate?.navigationViewController?(self, waypointSymbolStyleLayerWithIdentifier: identifier, source: source) } @objc public func navigationMapView(_ mapView: NavigationMapView, shapeFor waypoints: [Waypoint], legIndex: Int) -> MLNShape? { - delegate?.navigationViewController?(self, shapeFor: waypoints, legIndex: legIndex) + self.delegate?.navigationViewController?(self, shapeFor: waypoints, legIndex: legIndex) } @objc public func navigationMapView(_ mapView: MLNMapView, imageFor annotation: MLNAnnotation) -> MLNAnnotationImage? { - delegate?.navigationViewController?(self, imageFor: annotation) + self.delegate?.navigationViewController?(self, imageFor: annotation) } @objc public func navigationMapView(_ mapView: MLNMapView, viewFor annotation: MLNAnnotation) -> MLNAnnotationView? { - delegate?.navigationViewController?(self, viewFor: annotation) + self.delegate?.navigationViewController?(self, viewFor: annotation) } func mapViewControllerDidDismiss(_ mapViewController: RouteMapViewController, byCanceling canceled: Bool) { - if delegate?.navigationViewControllerDidDismiss?(self, byCanceling: canceled) != nil { + if self.delegate?.navigationViewControllerDidDismiss?(self, byCanceling: canceled) != nil { // The receiver should handle dismissal of the NavigationViewController } else { dismiss(animated: true, completion: nil) @@ -588,11 +588,11 @@ extension NavigationViewController: RouteMapViewControllerDelegate { } public func navigationMapViewUserAnchorPoint(_ mapView: NavigationMapView) -> CGPoint { - delegate?.navigationViewController?(self, mapViewUserAnchorPoint: mapView) ?? .zero + self.delegate?.navigationViewController?(self, mapViewUserAnchorPoint: mapView) ?? .zero } func mapViewControllerShouldAnnotateSpokenInstructions(_ routeMapViewController: RouteMapViewController) -> Bool { - annotatesSpokenInstructions + self.annotatesSpokenInstructions } @objc func mapViewController(_ mapViewController: RouteMapViewController, roadNameAt location: CLLocation) -> String? { @@ -603,7 +603,7 @@ extension NavigationViewController: RouteMapViewControllerDelegate { } @objc public func label(_ label: InstructionLabel, willPresent instruction: VisualInstruction, as presented: NSAttributedString) -> NSAttributedString? { - delegate?.label?(label, willPresent: instruction, as: presented) + self.delegate?.label?(label, willPresent: instruction, as: presented) } } @@ -611,24 +611,24 @@ extension NavigationViewController: RouteMapViewControllerDelegate { extension NavigationViewController: RouteControllerDelegate { @objc public func routeController(_ routeController: RouteController, shouldRerouteFrom location: CLLocation) -> Bool { - delegate?.navigationViewController?(self, shouldRerouteFrom: location) ?? true + self.delegate?.navigationViewController?(self, shouldRerouteFrom: location) ?? true } @objc public func routeController(_ routeController: RouteController, willRerouteFrom location: CLLocation) { - delegate?.navigationViewController?(self, willRerouteFrom: location) + self.delegate?.navigationViewController?(self, willRerouteFrom: location) } @objc public func routeController(_ routeController: RouteController, didRerouteAlong route: Route) { - mapViewController?.notifyDidReroute(route: route) - delegate?.navigationViewController?(self, didRerouteAlong: route) + self.mapViewController?.notifyDidReroute(route: route) + self.delegate?.navigationViewController?(self, didRerouteAlong: route) } @objc public func routeController(_ routeController: RouteController, didFailToRerouteWith error: Error) { - delegate?.navigationViewController?(self, didFailToRerouteWith: error) + self.delegate?.navigationViewController?(self, didFailToRerouteWith: error) } @objc public func routeController(_ routeController: RouteController, shouldDiscard location: CLLocation) -> Bool { - delegate?.navigationViewController?(self, shouldDiscard: location) ?? true + self.delegate?.navigationViewController?(self, shouldDiscard: location) ?? true } @objc public func routeController(_ routeController: RouteController, didUpdate locations: [CLLocation]) { @@ -638,22 +638,22 @@ extension NavigationViewController: RouteControllerDelegate { let shouldPreventReroutesWhenArrivingAtWaypoint = routeController.delegate?.routeController?(routeController, shouldPreventReroutesWhenArrivingAt: routeController.routeProgress.currentLeg.destination) ?? true let userHasArrivedAndShouldPreventRerouting = shouldPreventReroutesWhenArrivingAtWaypoint && !routeController.routeProgress.currentLegProgress.userHasArrivedAtWaypoint - if snapsUserLocationAnnotationToRoute, + if self.snapsUserLocationAnnotationToRoute, let snappedLocation = routeController.location ?? locations.last, let rawLocation = locations.last, userHasArrivedAndShouldPreventRerouting { - mapViewController?.labelCurrentRoad(at: rawLocation, for: snappedLocation) + self.mapViewController?.labelCurrentRoad(at: rawLocation, for: snappedLocation) } else if let rawlocation = locations.last { - mapViewController?.labelCurrentRoad(at: rawlocation) + self.mapViewController?.labelCurrentRoad(at: rawlocation) } } @objc public func routeController(_ routeController: RouteController, didArriveAt waypoint: Waypoint) -> Bool { - let advancesToNextLeg = delegate?.navigationViewController?(self, didArriveAt: waypoint) ?? true + let advancesToNextLeg = self.delegate?.navigationViewController?(self, didArriveAt: waypoint) ?? true - if !isConnectedToCarPlay, // CarPlayManager shows rating on CarPlay if it's connected - routeController.routeProgress.isFinalLeg, advancesToNextLeg, showsEndOfRouteFeedback { - mapViewController?.showEndOfRoute { _ in } + if !self.isConnectedToCarPlay, // CarPlayManager shows rating on CarPlay if it's connected + routeController.routeProgress.isFinalLeg, advancesToNextLeg, self.showsEndOfRouteFeedback { + self.mapViewController?.showEndOfRoute { _ in } } return advancesToNextLeg } @@ -661,13 +661,13 @@ extension NavigationViewController: RouteControllerDelegate { extension NavigationViewController: TunnelIntersectionManagerDelegate { public func tunnelIntersectionManager(_ manager: TunnelIntersectionManager, willEnableAnimationAt location: CLLocation) { - routeController.tunnelIntersectionManager(manager, willEnableAnimationAt: location) - styleManager.applyStyle(type: .night) + self.routeController.tunnelIntersectionManager(manager, willEnableAnimationAt: location) + self.styleManager.applyStyle(type: .night) } public func tunnelIntersectionManager(_ manager: TunnelIntersectionManager, willDisableAnimationAt location: CLLocation) { - routeController.tunnelIntersectionManager(manager, willDisableAnimationAt: location) - styleManager.timeOfDayChanged() + self.routeController.tunnelIntersectionManager(manager, willDisableAnimationAt: location) + self.styleManager.timeOfDayChanged() } } @@ -683,16 +683,16 @@ extension NavigationViewController: StyleManagerDelegate { } public func styleManager(_ styleManager: StyleManager, didApply style: Style) { - if mapView?.styleURL != style.mapStyleURL { - mapView?.style?.transition = MLNTransition(duration: 0.5, delay: 0) - mapView?.styleURL = style.mapStyleURL + if self.mapView?.styleURL != style.mapStyleURL { + self.mapView?.style?.transition = MLNTransition(duration: 0.5, delay: 0) + self.mapView?.styleURL = style.mapStyleURL } - currentStatusBarStyle = style.statusBarStyle ?? .default + self.currentStatusBarStyle = style.statusBarStyle ?? .default setNeedsStatusBarAppearanceUpdate() } public func styleManagerDidRefreshAppearance(_ styleManager: StyleManager) { - mapView?.reloadStyle(self) + self.mapView?.reloadStyle(self) } } diff --git a/MapboxNavigation/NextBannerView.swift b/MapboxNavigation/NextBannerView.swift index 2b0341c6..add95e1f 100644 --- a/MapboxNavigation/NextBannerView.swift +++ b/MapboxNavigation/NextBannerView.swift @@ -15,23 +15,23 @@ open class NextBannerView: UIView { weak var bottomSeparatorView: SeparatorView! weak var instructionDelegate: VisualInstructionDelegate? { didSet { - instructionLabel.instructionDelegate = instructionDelegate + self.instructionLabel.instructionDelegate = self.instructionDelegate } } override init(frame: CGRect) { super.init(frame: frame) - commonInit() + self.commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) - commonInit() + self.commonInit() } func commonInit() { - setupViews() - setupLayout() + self.setupViews() + self.setupLayout() } func setupViews() { @@ -43,7 +43,7 @@ open class NextBannerView: UIView { self.maneuverView = maneuverView let instructionLabel = NextInstructionLabel() - instructionLabel.instructionDelegate = instructionDelegate + instructionLabel.instructionDelegate = self.instructionDelegate instructionLabel.shieldHeight = instructionLabel.font.pointSize instructionLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(instructionLabel) @@ -63,10 +63,10 @@ open class NextBannerView: UIView { override open func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() - maneuverView.isEnd = true + self.maneuverView.isEnd = true let component = VisualInstructionComponent(type: .text, text: "Next step", imageURL: nil, abbreviation: nil, abbreviationPriority: NSNotFound) let instruction = VisualInstruction(text: nil, maneuverType: .none, maneuverDirection: .none, components: [component]) - instructionLabel.instruction = instruction + self.instructionLabel.instruction = instruction } func setupLayout() { @@ -75,19 +75,19 @@ open class NextBannerView: UIView { heightConstraint.isActive = true let midX = BaseInstructionsBannerView.padding + BaseInstructionsBannerView.maneuverViewSize.width / 2 - maneuverView.centerXAnchor.constraint(equalTo: leadingAnchor, constant: midX).isActive = true - maneuverView.heightAnchor.constraint(equalToConstant: 22).isActive = true - maneuverView.widthAnchor.constraint(equalToConstant: 22).isActive = true - maneuverView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true + self.maneuverView.centerXAnchor.constraint(equalTo: leadingAnchor, constant: midX).isActive = true + self.maneuverView.heightAnchor.constraint(equalToConstant: 22).isActive = true + self.maneuverView.widthAnchor.constraint(equalToConstant: 22).isActive = true + self.maneuverView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true - instructionLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 70).isActive = true - instructionLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true - instructionLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16).isActive = true + self.instructionLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 70).isActive = true + self.instructionLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true + self.instructionLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16).isActive = true - bottomSeparatorView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true - bottomSeparatorView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true - bottomSeparatorView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true - bottomSeparatorView.heightAnchor.constraint(equalToConstant: 1 / UIScreen.main.scale).isActive = true + self.bottomSeparatorView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true + self.bottomSeparatorView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true + self.bottomSeparatorView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true + self.bottomSeparatorView.heightAnchor.constraint(equalToConstant: 1 / UIScreen.main.scale).isActive = true } /** @@ -96,14 +96,14 @@ open class NextBannerView: UIView { @objc(updateForVisualInstructionBanner:) public func update(for visualInstruction: VisualInstructionBanner?) { guard let tertiaryInstruction = visualInstruction?.tertiaryInstruction, !tertiaryInstruction.containsLaneIndications else { - hide() + self.hide() return } - maneuverView.visualInstruction = tertiaryInstruction - maneuverView.drivingSide = visualInstruction?.drivingSide ?? .right - instructionLabel.instruction = tertiaryInstruction - show() + self.maneuverView.visualInstruction = tertiaryInstruction + self.maneuverView.drivingSide = visualInstruction?.drivingSide ?? .right + self.instructionLabel.instruction = tertiaryInstruction + self.show() } public func show() { diff --git a/MapboxNavigation/RatingControl.swift b/MapboxNavigation/RatingControl.swift index 0b29abdf..12560faf 100644 --- a/MapboxNavigation/RatingControl.swift +++ b/MapboxNavigation/RatingControl.swift @@ -18,8 +18,8 @@ class RatingControl: UIStackView { var rating: Int = 0 { didSet { - updateSelectionStates() - didChangeRating?(rating) + self.updateSelectionStates() + self.didChangeRating?(self.rating) } } @@ -37,13 +37,13 @@ class RatingControl: UIStackView { @objc public dynamic var starSize: CGSize = defaultSize { didSet { - configureStars() + self.configureStars() } } @objc public dynamic var starCount: Int = 5 { didSet { - configureStars() + self.configureStars() } } @@ -51,28 +51,28 @@ class RatingControl: UIStackView { override public init(frame: CGRect) { super.init(frame: frame) - configureStars() + self.configureStars() } public required init(coder: NSCoder) { super.init(coder: coder) - configureStars() + self.configureStars() } // MARK: Private Functions private func configureStars() { - removeStars() - addStars() - updateSelectionStates() + self.removeStars() + self.addStars() + self.updateSelectionStates() } private func addStars() { - for index in 0 ..< starCount { + for index in 0 ..< self.starCount { let button = UIButton(type: .custom) - button.setImage(starTemplate, for: .normal) + button.setImage(self.starTemplate, for: .normal) button.adjustsImageWhenHighlighted = false - addButtonSizeConstraints(to: button) + self.addButtonSizeConstraints(to: button) let setRatingNumber = index + 1 let localizedString = NSLocalizedString("RATING_ACCESSIBILITY_SET", bundle: .mapboxNavigation, value: "Set %ld-star rating", comment: "Format for accessibility label of button for setting a rating; 1 = number of stars") @@ -82,55 +82,55 @@ class RatingControl: UIStackView { addArrangedSubview(button) - stars.append(button) + self.stars.append(button) } } private func removeStars() { - for star in stars { + for star in self.stars { removeArrangedSubview(star) star.removeFromSuperview() } - stars.removeAll() + self.stars.removeAll() } private func updateSelectionStates() { - for (index, button) in stars.enumerated() { - let selected = index < rating - button.tintColor = selected ? selectedColor : normalColor + for (index, button) in self.stars.enumerated() { + let selected = index < self.rating + button.tintColor = selected ? self.selectedColor : self.normalColor button.isSelected = selected - setAccessibility(for: button, at: index) + self.setAccessibility(for: button, at: index) } } private func setAccessibility(for button: UIButton, at index: Int) { - setAccessibilityHint(for: button, at: index) + self.setAccessibilityHint(for: button, at: index) - let value: String = if rating == 0 { + let value: String = if self.rating == 0 { NSLocalizedString("NO_RATING", bundle: .mapboxNavigation, value: "No rating set.", comment: "Accessibility value of label indicating the absence of a rating") } else { - String.localizedStringWithFormat(NSLocalizedString("RATING_STARS_FORMAT", bundle: .mapboxNavigation, value: "%ld star(s) set.", comment: "Format for accessibility value of label indicating the existing rating; 1 = number of stars"), rating) + String.localizedStringWithFormat(NSLocalizedString("RATING_STARS_FORMAT", bundle: .mapboxNavigation, value: "%ld star(s) set.", comment: "Format for accessibility value of label indicating the existing rating; 1 = number of stars"), self.rating) } button.accessibilityValue = value } private func setAccessibilityHint(for button: UIButton, at index: Int) { - guard rating == (index + 1) else { return } // This applies only to the zero-resettable button. + guard self.rating == (index + 1) else { return } // This applies only to the zero-resettable button. button.accessibilityHint = NSLocalizedString("RATING_ACCESSIBILITY_RESET", bundle: .mapboxNavigation, value: "Tap to reset the rating to zero.", comment: "Rating Reset To Zero Accessability Hint") } private func addButtonSizeConstraints(to view: UIView) { - view.widthAnchor.constraint(equalToConstant: starSize.width).isActive = true - view.heightAnchor.constraint(equalToConstant: starSize.height).isActive = true + view.widthAnchor.constraint(equalToConstant: self.starSize.width).isActive = true + view.heightAnchor.constraint(equalToConstant: self.starSize.height).isActive = true } @objc private func ratingButtonTapped(button sender: UIButton) { guard let index = stars.firstIndex(of: sender) else { return assertionFailure("RatingControl.swift: The Star button that was tapped was not found in the RatingControl.stars array. This should never happen.") } let selectedRating = index + 1 - rating = (selectedRating == rating) ? 0 : selectedRating + self.rating = (selectedRating == self.rating) ? 0 : selectedRating } } diff --git a/MapboxNavigation/RouteMapViewController.swift b/MapboxNavigation/RouteMapViewController.swift index a8534be1..57ae91cf 100644 --- a/MapboxNavigation/RouteMapViewController.swift +++ b/MapboxNavigation/RouteMapViewController.swift @@ -10,13 +10,13 @@ class ArrowStrokePolyline: ArrowFillPolyline {} class RouteMapViewController: UIViewController { var navigationView: NavigationView { view as! NavigationView } - var mapView: NavigationMapView { navigationView.mapView } - var statusView: StatusView { navigationView.statusView } - var reportButton: FloatingButton { navigationView.reportButton } - var lanesView: LanesView { navigationView.lanesView } - var nextBannerView: NextBannerView { navigationView.nextBannerView } - var instructionsBannerView: InstructionsBannerView { navigationView.instructionsBannerView } - var instructionsBannerContentView: InstructionsBannerContentView { navigationView.instructionsBannerContentView } + var mapView: NavigationMapView { self.navigationView.mapView } + var statusView: StatusView { self.navigationView.statusView } + var reportButton: FloatingButton { self.navigationView.reportButton } + var lanesView: LanesView { self.navigationView.lanesView } + var nextBannerView: NextBannerView { self.navigationView.nextBannerView } + var instructionsBannerView: InstructionsBannerView { self.navigationView.instructionsBannerView } + var instructionsBannerContentView: InstructionsBannerContentView { self.navigationView.instructionsBannerContentView } lazy var endOfRouteViewController: EndOfRouteViewController = { let storyboard = UIStoryboard(name: "Navigation", bundle: .mapboxNavigation) @@ -30,7 +30,7 @@ class RouteMapViewController: UIViewController { static let recenter: Selector = #selector(RouteMapViewController.recenter(_:)) } - var route: Route { routeController.routeProgress.route } + var route: Route { self.routeController.routeProgress.route } var updateETATimer: Timer? var previewInstructionsView: StepInstructionsView? var lastTimeUserRerouted: Date? @@ -39,10 +39,10 @@ class RouteMapViewController: UIViewController { var destination: Waypoint? var isUsedInConjunctionWithCarPlayWindow = false { didSet { - if isUsedInConjunctionWithCarPlayWindow { + if self.isUsedInConjunctionWithCarPlayWindow { displayPreviewInstructions() } else { - stepsViewController?.dismiss() + self.stepsViewController?.dismiss() } } } @@ -57,7 +57,7 @@ class RouteMapViewController: UIViewController { } var tiltedCamera: MLNMapCamera { - let camera = mapView.camera + let camera = self.mapView.camera camera.altitude = 1000 camera.pitch = 45 return camera @@ -66,9 +66,9 @@ class RouteMapViewController: UIViewController { weak var delegate: RouteMapViewControllerDelegate? var routeController: Router! { didSet { - navigationView.statusView.canChangeValue = routeController.locationManager is SimulatedLocationManager + self.navigationView.statusView.canChangeValue = self.routeController.locationManager is SimulatedLocationManager guard let destination = route.legs.last?.destination else { return } - populateName(for: destination, populated: { self.destination = $0 }) + self.populateName(for: destination, populated: { self.destination = $0 }) } } @@ -76,15 +76,15 @@ class RouteMapViewController: UIViewController { var arrowCurrentStep: RouteStep? var isInOverviewMode = false { didSet { - if isInOverviewMode { - navigationView.overviewButton.isHidden = true - navigationView.resumeButton.isHidden = false - navigationView.wayNameView.isHidden = true - mapView.logoView.isHidden = true + if self.isInOverviewMode { + self.navigationView.overviewButton.isHidden = true + self.navigationView.resumeButton.isHidden = false + self.navigationView.wayNameView.isHidden = true + self.mapView.logoView.isHidden = true } else { - navigationView.overviewButton.isHidden = false - navigationView.resumeButton.isHidden = true - mapView.logoView.isHidden = false + self.navigationView.overviewButton.isHidden = false + self.navigationView.resumeButton.isHidden = true + self.mapView.logoView.isHidden = false } } } @@ -98,7 +98,7 @@ class RouteMapViewController: UIViewController { var annotatesSpokenInstructions = false var overheadInsets: UIEdgeInsets { - UIEdgeInsets(top: navigationView.instructionsBannerView.bounds.height, left: 20, bottom: navigationView.bottomBannerView.bounds.height, right: 20) + UIEdgeInsets(top: self.navigationView.instructionsBannerView.bounds.height, left: 20, bottom: self.navigationView.bottomBannerView.bounds.height, right: 20) } typealias LabelRoadNameCompletionHandler = (_ defaultRaodNameAssigned: Bool) -> Void @@ -120,18 +120,18 @@ class RouteMapViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() - mapView.contentInset = contentInsets + self.mapView.contentInset = self.contentInsets view.layoutIfNeeded() - mapView.tracksUserCourse = true + self.mapView.tracksUserCourse = true - distanceFormatter.numberFormatter.locale = .nationalizedCurrent + self.distanceFormatter.numberFormatter.locale = .nationalizedCurrent - navigationView.overviewButton.addTarget(self, action: Actions.overview, for: .touchUpInside) - navigationView.muteButton.addTarget(self, action: Actions.mute, for: .touchUpInside) - navigationView.resumeButton.addTarget(self, action: Actions.recenter, for: .touchUpInside) - resumeNotifications() - notifyUserAboutLowVolume() + self.navigationView.overviewButton.addTarget(self, action: Actions.overview, for: .touchUpInside) + self.navigationView.muteButton.addTarget(self, action: Actions.mute, for: .touchUpInside) + self.navigationView.resumeButton.addTarget(self, action: Actions.recenter, for: .touchUpInside) + self.resumeNotifications() + self.notifyUserAboutLowVolume() } deinit { @@ -144,45 +144,45 @@ class RouteMapViewController: UIViewController { resetETATimer() - navigationView.muteButton.isSelected = NavigationSettings.shared.voiceMuted - mapView.compassView.isHidden = true + self.navigationView.muteButton.isSelected = NavigationSettings.shared.voiceMuted + self.mapView.compassView.isHidden = true - mapView.tracksUserCourse = true + self.mapView.tracksUserCourse = true if let camera = pendingCamera { - mapView.camera = camera + self.mapView.camera = camera } else if let location = routeController.location, location.course > 0 { - mapView.updateCourseTracking(location: location, animated: false) + self.mapView.updateCourseTracking(location: location, animated: false) } else if let coordinates = routeController.routeProgress.currentLegProgress.currentStep.coordinates, let firstCoordinate = coordinates.first, coordinates.count > 1 { let secondCoordinate = coordinates[1] let course = firstCoordinate.direction(to: secondCoordinate) let newLocation = CLLocation(coordinate: routeController.location?.coordinate ?? firstCoordinate, altitude: 0, horizontalAccuracy: 0, verticalAccuracy: 0, course: course, speed: 0, timestamp: Date()) - mapView.updateCourseTracking(location: newLocation, animated: false) + self.mapView.updateCourseTracking(location: newLocation, animated: false) } else { - mapView.setCamera(tiltedCamera, animated: false) + self.mapView.setCamera(self.tiltedCamera, animated: false) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) - annotatesSpokenInstructions = delegate?.mapViewControllerShouldAnnotateSpokenInstructions(self) ?? false + self.annotatesSpokenInstructions = self.delegate?.mapViewControllerShouldAnnotateSpokenInstructions(self) ?? false showRouteIfNeeded() - currentLegIndexMapped = routeController.routeProgress.legIndex - currentStepIndexMapped = routeController.routeProgress.currentLegProgress.stepIndex + self.currentLegIndexMapped = self.routeController.routeProgress.legIndex + self.currentStepIndexMapped = self.routeController.routeProgress.currentLegProgress.stepIndex } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) - removeTimer() + self.removeTimer() } func resumeNotifications() { - NotificationCenter.default.addObserver(self, selector: #selector(willReroute(notification:)), name: .routeControllerWillReroute, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(didReroute(notification:)), name: .routeControllerDidReroute, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(rerouteDidFail(notification:)), name: .routeControllerDidFailToReroute, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground(notification:)), name: UIApplication.willEnterForegroundNotification, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(removeTimer), name: UIApplication.didEnterBackgroundNotification, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(updateInstructionsBanner(notification:)), name: .routeControllerDidPassVisualInstructionPoint, object: routeController) + NotificationCenter.default.addObserver(self, selector: #selector(self.willReroute(notification:)), name: .routeControllerWillReroute, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(self.didReroute(notification:)), name: .routeControllerDidReroute, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(self.rerouteDidFail(notification:)), name: .routeControllerDidFailToReroute, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(self.applicationWillEnterForeground(notification:)), name: UIApplication.willEnterForegroundNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(self.removeTimer), name: UIApplication.didEnterBackgroundNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(self.updateInstructionsBanner(notification:)), name: .routeControllerDidPassVisualInstructionPoint, object: self.routeController) subscribeToKeyboardNotifications() } @@ -197,38 +197,38 @@ class RouteMapViewController: UIViewController { } @objc func recenter(_ sender: AnyObject) { - mapView.tracksUserCourse = true - mapView.enableFrameByFrameCourseViewTracking(for: 3) - isInOverviewMode = false - updateCameraAltitude(for: routeController.routeProgress) + self.mapView.tracksUserCourse = true + self.mapView.enableFrameByFrameCourseViewTracking(for: 3) + self.isInOverviewMode = false + self.updateCameraAltitude(for: self.routeController.routeProgress) - mapView.addArrow(route: routeController.routeProgress.route, - legIndex: routeController.routeProgress.legIndex, - stepIndex: routeController.routeProgress.currentLegProgress.stepIndex + 1) + self.mapView.addArrow(route: self.routeController.routeProgress.route, + legIndex: self.routeController.routeProgress.legIndex, + stepIndex: self.routeController.routeProgress.currentLegProgress.stepIndex + 1) - removePreviewInstructions() + self.removePreviewInstructions() } @objc func removeTimer() { - updateETATimer?.invalidate() - updateETATimer = nil + self.updateETATimer?.invalidate() + self.updateETATimer = nil } func removePreviewInstructions() { if let view = previewInstructionsView { view.removeFromSuperview() - navigationView.instructionsBannerContentView.backgroundColor = InstructionsBannerView.appearance().backgroundColor - navigationView.instructionsBannerView.delegate = self - previewInstructionsView = nil + self.navigationView.instructionsBannerContentView.backgroundColor = InstructionsBannerView.appearance().backgroundColor + self.navigationView.instructionsBannerView.delegate = self + self.previewInstructionsView = nil } } @objc func toggleOverview(_ sender: Any) { - mapView.enableFrameByFrameCourseViewTracking(for: 3) + self.mapView.enableFrameByFrameCourseViewTracking(for: 3) if let coordinates = routeController.routeProgress.route.coordinates, let userLocation = routeController.locationManager.location?.coordinate { - mapView.setOverheadCameraView(from: userLocation, along: coordinates, for: overheadInsets) + self.mapView.setOverheadCameraView(from: userLocation, along: coordinates, for: self.overheadInsets) } - isInOverviewMode = true + self.isInOverviewMode = true } @objc func toggleMute(_ sender: UIButton) { @@ -240,39 +240,39 @@ class RouteMapViewController: UIViewController { override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) - mapView.enableFrameByFrameCourseViewTracking(for: 3) + self.mapView.enableFrameByFrameCourseViewTracking(for: 3) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() - mapView.setContentInset(contentInsets, animated: true, completionHandler: nil) - mapView.setNeedsUpdateConstraints() + self.mapView.setContentInset(self.contentInsets, animated: true, completionHandler: nil) + self.mapView.setNeedsUpdateConstraints() } func notifyDidReroute(route: Route) { updateETA() - currentStepIndexMapped = 0 + self.currentStepIndexMapped = 0 - instructionsBannerView.updateDistance(for: routeController.routeProgress.currentLegProgress.currentStepProgress) + self.instructionsBannerView.updateDistance(for: self.routeController.routeProgress.currentLegProgress.currentStepProgress) - mapView.addArrow(route: routeController.routeProgress.route, legIndex: routeController.routeProgress.legIndex, stepIndex: routeController.routeProgress.currentLegProgress.stepIndex + 1) - mapView.showRoutes([routeController.routeProgress.route], legIndex: routeController.routeProgress.legIndex) - mapView.showWaypoints(routeController.routeProgress.route) + self.mapView.addArrow(route: self.routeController.routeProgress.route, legIndex: self.routeController.routeProgress.legIndex, stepIndex: self.routeController.routeProgress.currentLegProgress.stepIndex + 1) + self.mapView.showRoutes([self.routeController.routeProgress.route], legIndex: self.routeController.routeProgress.legIndex) + self.mapView.showWaypoints(self.routeController.routeProgress.route) - if annotatesSpokenInstructions { - mapView.showVoiceInstructionsOnMap(route: routeController.routeProgress.route) + if self.annotatesSpokenInstructions { + self.mapView.showVoiceInstructionsOnMap(route: self.routeController.routeProgress.route) } - if isInOverviewMode { + if self.isInOverviewMode { if let coordinates = routeController.routeProgress.route.coordinates, let userLocation = routeController.locationManager.location?.coordinate { - mapView.setOverheadCameraView(from: userLocation, along: coordinates, for: overheadInsets) + self.mapView.setOverheadCameraView(from: userLocation, along: coordinates, for: self.overheadInsets) } } else { - mapView.tracksUserCourse = true - navigationView.wayNameView.isHidden = true + self.mapView.tracksUserCourse = true + self.navigationView.wayNameView.isHidden = true } - stepsViewController?.dismiss { + self.stepsViewController?.dismiss { self.removePreviewInstructions() self.stepsViewController = nil self.navigationView.instructionsBannerView.stepListIndicatorView.isHidden = false @@ -280,28 +280,28 @@ class RouteMapViewController: UIViewController { } @objc func applicationWillEnterForeground(notification: NSNotification) { - mapView.updateCourseTracking(location: routeController.location, animated: false) + self.mapView.updateCourseTracking(location: self.routeController.location, animated: false) resetETATimer() } @objc func willReroute(notification: NSNotification) { let title = NSLocalizedString("REROUTING", bundle: .mapboxNavigation, value: "Rerouting…", comment: "Indicates that rerouting is in progress") - lanesView.hide() - statusView.show(title, showSpinner: true) + self.lanesView.hide() + self.statusView.show(title, showSpinner: true) } @objc func rerouteDidFail(notification: NSNotification) { - statusView.hide() + self.statusView.hide() } func notifyUserAboutLowVolume() { - guard !(routeController.locationManager is SimulatedLocationManager) else { return } + guard !(self.routeController.locationManager is SimulatedLocationManager) else { return } guard !NavigationSettings.shared.voiceMuted else { return } guard AVAudioSession.sharedInstance().outputVolume <= NavigationViewMinimumVolumeForWarning else { return } let title = String.localizedStringWithFormat(NSLocalizedString("DEVICE_VOLUME_LOW", bundle: .mapboxNavigation, value: "%@ Volume Low", comment: "Format string for indicating the device volume is low; 1 = device model"), UIDevice.current.model) - statusView.show(title, showSpinner: false) - statusView.hide(delay: 3, animated: true) + self.statusView.show(title, showSpinner: false) + self.statusView.hide(delay: 3, animated: true) } @objc func didReroute(notification: NSNotification) { @@ -309,38 +309,38 @@ class RouteMapViewController: UIViewController { if let locationManager = routeController.locationManager as? SimulatedLocationManager { let localized = String.Localized.simulationStatus(speed: Int(locationManager.speedMultiplier)) - showStatus(title: localized, for: .infinity, interactive: true) + self.showStatus(title: localized, for: .infinity, interactive: true) } else { - statusView.hide(delay: 2, animated: true) + self.statusView.hide(delay: 2, animated: true) } if notification.userInfo![RouteControllerNotificationUserInfoKey.isProactiveKey] as! Bool { let title = NSLocalizedString("FASTER_ROUTE_FOUND", bundle: .mapboxNavigation, value: "Faster Route Found", comment: "Indicates a faster route was found") - showStatus(title: title, withSpinner: true, for: 3) + self.showStatus(title: title, withSpinner: true, for: 3) } } @objc func updateInstructionsBanner(notification: NSNotification) { guard let routeProgress = notification.userInfo?[RouteControllerNotificationUserInfoKey.routeProgressKey] as? RouteProgress else { return } - instructionsBannerView.update(for: routeProgress.currentLegProgress.currentStepProgress.currentVisualInstruction) - lanesView.update(for: routeProgress.currentLegProgress.currentStepProgress.currentVisualInstruction) - nextBannerView.update(for: routeProgress.currentLegProgress.currentStepProgress.currentVisualInstruction) + self.instructionsBannerView.update(for: routeProgress.currentLegProgress.currentStepProgress.currentVisualInstruction) + self.lanesView.update(for: routeProgress.currentLegProgress.currentStepProgress.currentVisualInstruction) + self.nextBannerView.update(for: routeProgress.currentLegProgress.currentStepProgress.currentVisualInstruction) } func updateMapOverlays(for routeProgress: RouteProgress) { if routeProgress.currentLegProgress.followOnStep != nil { - mapView.addArrow(route: routeController.routeProgress.route, legIndex: routeController.routeProgress.legIndex, stepIndex: routeController.routeProgress.currentLegProgress.stepIndex + 1) + self.mapView.addArrow(route: self.routeController.routeProgress.route, legIndex: self.routeController.routeProgress.legIndex, stepIndex: self.routeController.routeProgress.currentLegProgress.stepIndex + 1) } else { - mapView.removeArrow() + self.mapView.removeArrow() } } func updateCameraAltitude(for routeProgress: RouteProgress) { - guard mapView.tracksUserCourse else { return } // only adjust when we are actively tracking user course + guard self.mapView.tracksUserCourse else { return } // only adjust when we are actively tracking user course - let zoomOutAltitude = mapView.zoomedOutMotorwayAltitude - let defaultAltitude = mapView.defaultAltitude - let isLongRoad = routeProgress.distanceRemaining >= mapView.longManeuverDistance + let zoomOutAltitude = self.mapView.zoomedOutMotorwayAltitude + let defaultAltitude = self.mapView.defaultAltitude + let isLongRoad = routeProgress.distanceRemaining >= self.mapView.longManeuverDistance let currentStep = routeProgress.currentLegProgress.currentStep let upComingStep = routeProgress.currentLegProgress.upComingStep @@ -352,21 +352,21 @@ class RouteMapViewController: UIViewController { let currentStepIsMotorway = currentStep.isMotorway let nextStepIsMotorway = upComingStep?.isMotorway ?? false if currentStepIsMotorway, nextStepIsMotorway, isLongRoad { - setCamera(altitude: zoomOutAltitude) + self.setCamera(altitude: zoomOutAltitude) } else if currentInstruction == currentStep.lastInstruction { - setCamera(altitude: defaultAltitude) + self.setCamera(altitude: defaultAltitude) } } private func showStatus(title: String, withSpinner spin: Bool = false, for time: TimeInterval, animated: Bool = true, interactive: Bool = false) { - statusView.show(title, showSpinner: spin, interactive: interactive) + self.statusView.show(title, showSpinner: spin, interactive: interactive) guard time < .infinity else { return } - statusView.hide(delay: time, animated: animated) + self.statusView.hide(delay: time, animated: animated) } private func setCamera(altitude: Double) { - guard mapView.altitude != altitude else { return } - mapView.altitude = altitude + guard self.mapView.altitude != altitude else { return } + self.mapView.altitude = altitude } func mapView(_ mapView: MLNMapView, imageFor annotation: MLNAnnotation) -> MLNAnnotationImage? { @@ -381,38 +381,38 @@ class RouteMapViewController: UIViewController { resetETATimer() updateETA() - instructionsBannerView.updateDistance(for: routeProgress.currentLegProgress.currentStepProgress) + self.instructionsBannerView.updateDistance(for: routeProgress.currentLegProgress.currentStepProgress) - if currentLegIndexMapped != routeProgress.legIndex { - mapView.showWaypoints(routeProgress.route, legIndex: routeProgress.legIndex) - mapView.showRoutes([routeProgress.route], legIndex: routeProgress.legIndex) + if self.currentLegIndexMapped != routeProgress.legIndex { + self.mapView.showWaypoints(routeProgress.route, legIndex: routeProgress.legIndex) + self.mapView.showRoutes([routeProgress.route], legIndex: routeProgress.legIndex) - currentLegIndexMapped = routeProgress.legIndex + self.currentLegIndexMapped = routeProgress.legIndex } - if currentStepIndexMapped != routeProgress.currentLegProgress.stepIndex { - updateMapOverlays(for: routeProgress) - currentStepIndexMapped = routeProgress.currentLegProgress.stepIndex + if self.currentStepIndexMapped != routeProgress.currentLegProgress.stepIndex { + self.updateMapOverlays(for: routeProgress) + self.currentStepIndexMapped = routeProgress.currentLegProgress.stepIndex } - if annotatesSpokenInstructions { - mapView.showVoiceInstructionsOnMap(route: routeController.routeProgress.route) + if self.annotatesSpokenInstructions { + self.mapView.showVoiceInstructionsOnMap(route: self.routeController.routeProgress.route) } } var contentInsets: UIEdgeInsets { - let top = navigationView.instructionsBannerContentView.bounds.height - let bottom = navigationView.bottomBannerView.bounds.height + let top = self.navigationView.instructionsBannerContentView.bounds.height + let bottom = self.navigationView.bottomBannerView.bounds.height return UIEdgeInsets(top: top, left: 0, bottom: bottom, right: 0) } // MARK: End Of Route func embedEndOfRoute() { - let endOfRoute = endOfRouteViewController + let endOfRoute = self.endOfRouteViewController addChild(endOfRoute) - navigationView.endOfRouteView = endOfRoute.view - navigationView.constrainEndOfRoute() + self.navigationView.endOfRouteView = endOfRoute.view + self.navigationView.constrainEndOfRoute() endOfRoute.didMove(toParent: self) endOfRoute.dismissHandler = { [weak self] _, _ in @@ -422,24 +422,24 @@ class RouteMapViewController: UIViewController { } func unembedEndOfRoute() { - let endOfRoute = endOfRouteViewController + let endOfRoute = self.endOfRouteViewController endOfRoute.willMove(toParent: nil) endOfRoute.removeFromParent() } func showEndOfRoute(duration: TimeInterval = 1.0, completion: ((Bool) -> Void)? = nil) { - embedEndOfRoute() - endOfRouteViewController.destination = destination - navigationView.endOfRouteView?.isHidden = false + self.embedEndOfRoute() + self.endOfRouteViewController.destination = self.destination + self.navigationView.endOfRouteView?.isHidden = false view.layoutIfNeeded() // flush layout queue - NSLayoutConstraint.deactivate(navigationView.bannerShowConstraints) - NSLayoutConstraint.activate(navigationView.bannerHideConstraints) - navigationView.endOfRouteHideConstraint?.isActive = false - navigationView.endOfRouteShowConstraint?.isActive = true + NSLayoutConstraint.deactivate(self.navigationView.bannerShowConstraints) + NSLayoutConstraint.activate(self.navigationView.bannerHideConstraints) + self.navigationView.endOfRouteHideConstraint?.isActive = false + self.navigationView.endOfRouteShowConstraint?.isActive = true - mapView.enableFrameByFrameCourseViewTracking(for: duration) - mapView.setNeedsUpdateConstraints() + self.mapView.enableFrameByFrameCourseViewTracking(for: duration) + self.mapView.setNeedsUpdateConstraints() let animate = { self.view.layoutIfNeeded() @@ -450,7 +450,7 @@ class RouteMapViewController: UIViewController { guard duration > 0.0 else { return noAnimation() } - navigationView.mapView.tracksUserCourse = false + self.navigationView.mapView.tracksUserCourse = false UIView.animate(withDuration: duration, delay: 0.0, options: [.curveLinear], animations: animate, completion: completion) guard let height = navigationView.endOfRouteHeightConstraint?.constant else { return } @@ -460,21 +460,21 @@ class RouteMapViewController: UIViewController { let slicedLine = Polyline(coordinates).sliced(from: userLocation).coordinates let line = MLNPolyline(coordinates: slicedLine, count: UInt(slicedLine.count)) - let camera = navigationView.mapView.cameraThatFitsShape(line, direction: navigationView.mapView.camera.heading, edgePadding: insets) + let camera = self.navigationView.mapView.cameraThatFitsShape(line, direction: self.navigationView.mapView.camera.heading, edgePadding: insets) camera.pitch = 0 - camera.altitude = navigationView.mapView.camera.altitude - navigationView.mapView.setCamera(camera, animated: true) + camera.altitude = self.navigationView.mapView.camera.altitude + self.navigationView.mapView.setCamera(camera, animated: true) } } func hideEndOfRoute(duration: TimeInterval = 0.3, completion: ((Bool) -> Void)? = nil) { view.layoutIfNeeded() // flush layout queue - navigationView.endOfRouteHideConstraint?.isActive = true - navigationView.endOfRouteShowConstraint?.isActive = false + self.navigationView.endOfRouteHideConstraint?.isActive = true + self.navigationView.endOfRouteShowConstraint?.isActive = false view.clipsToBounds = true - mapView.enableFrameByFrameCourseViewTracking(for: duration) - mapView.setNeedsUpdateConstraints() + self.mapView.enableFrameByFrameCourseViewTracking(for: duration) + self.mapView.setNeedsUpdateConstraints() let animate = { self.view.layoutIfNeeded() @@ -510,7 +510,7 @@ class RouteMapViewController: UIViewController { extension RouteMapViewController { override func preferredContentSizeDidChange(forChildContentContainer container: UIContentContainer) { - navigationView.endOfRouteHeightConstraint?.constant = container.preferredContentSize.height + self.navigationView.endOfRouteHeightConstraint?.constant = container.preferredContentSize.height UIView.animate(withDuration: 0.3, animations: view.layoutIfNeeded) } @@ -522,7 +522,7 @@ extension RouteMapViewController: NavigationViewDelegate { // MARK: NavigationViewDelegate func navigationView(_ view: NavigationView, didTapCancelButton: CancelButton) { - delegate?.mapViewControllerDidDismiss(self, byCanceling: true) + self.delegate?.mapViewControllerDidDismiss(self, byCanceling: true) } // MARK: MLNMapViewDelegate @@ -532,63 +532,63 @@ extension RouteMapViewController: NavigationViewDelegate { if let mapView = mapView as? NavigationMapView, mapView.tracksUserCourse { userTrackingMode = .followWithCourse } - if userTrackingMode == .none, !isInOverviewMode { - navigationView.wayNameView.isHidden = true + if userTrackingMode == .none, !self.isInOverviewMode { + self.navigationView.wayNameView.isHidden = true } } func mapView(_ mapView: MLNMapView, didFinishLoading style: MLNStyle) { // This method is called before the view is added to a window // (if the style is cached) preventing UIAppearance to apply the style. - showRouteIfNeeded() + self.showRouteIfNeeded() self.mapView.localizeLabels() - delegate?.mapView?(mapView, didFinishLoading: style) + self.delegate?.mapView?(mapView, didFinishLoading: style) } func mapViewDidFinishLoadingMap(_ mapView: MLNMapView) { - delegate?.mapViewDidFinishLoadingMap?(mapView) + self.delegate?.mapViewDidFinishLoadingMap?(mapView) } func label(_ label: InstructionLabel, willPresent instruction: VisualInstruction, as presented: NSAttributedString) -> NSAttributedString? { - delegate?.label?(label, willPresent: instruction, as: presented) + self.delegate?.label?(label, willPresent: instruction, as: presented) } // MARK: NavigationMapViewCourseTrackingDelegate func navigationMapViewDidStartTrackingCourse(_ mapView: NavigationMapView) { - navigationView.resumeButton.isHidden = true + self.navigationView.resumeButton.isHidden = true mapView.logoView.isHidden = false } func navigationMapViewDidStopTrackingCourse(_ mapView: NavigationMapView) { - navigationView.resumeButton.isHidden = false - navigationView.wayNameView.isHidden = true + self.navigationView.resumeButton.isHidden = false + self.navigationView.wayNameView.isHidden = true mapView.logoView.isHidden = true } // MARK: InstructionsBannerViewDelegate func didDragInstructionsBanner(_ sender: BaseInstructionsBannerView) { - displayPreviewInstructions() + self.displayPreviewInstructions() } func didTapInstructionsBanner(_ sender: BaseInstructionsBannerView) { - displayPreviewInstructions() + self.displayPreviewInstructions() } private func displayPreviewInstructions() { - removePreviewInstructions() + self.removePreviewInstructions() if let controller = stepsViewController { - stepsViewController = nil + self.stepsViewController = nil controller.dismiss() } else { let controller = StepsViewController(routeProgress: routeController.routeProgress) controller.delegate = self addChild(controller) - view.insertSubview(controller.view, belowSubview: navigationView.instructionsBannerContentView) + view.insertSubview(controller.view, belowSubview: self.navigationView.instructionsBannerContentView) - controller.view.topAnchor.constraint(equalTo: navigationView.instructionsBannerContentView.bottomAnchor).isActive = true + controller.view.topAnchor.constraint(equalTo: self.navigationView.instructionsBannerContentView.bottomAnchor).isActive = true controller.view.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true controller.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true controller.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true @@ -596,7 +596,7 @@ extension RouteMapViewController: NavigationViewDelegate { controller.didMove(toParent: self) controller.dropDownAnimation() - stepsViewController = controller + self.stepsViewController = controller return } } @@ -604,53 +604,53 @@ extension RouteMapViewController: NavigationViewDelegate { // MARK: NavigationMapViewDelegate func navigationMapView(_ mapView: NavigationMapView, routeStyleLayerWithIdentifier identifier: String, source: MLNSource) -> MLNStyleLayer? { - delegate?.navigationMapView?(mapView, routeStyleLayerWithIdentifier: identifier, source: source) + self.delegate?.navigationMapView?(mapView, routeStyleLayerWithIdentifier: identifier, source: source) } func navigationMapView(_ mapView: NavigationMapView, routeCasingStyleLayerWithIdentifier identifier: String, source: MLNSource) -> MLNStyleLayer? { - delegate?.navigationMapView?(mapView, routeCasingStyleLayerWithIdentifier: identifier, source: source) + self.delegate?.navigationMapView?(mapView, routeCasingStyleLayerWithIdentifier: identifier, source: source) } func navigationMapView(_ mapView: NavigationMapView, waypointStyleLayerWithIdentifier identifier: String, source: MLNSource) -> MLNStyleLayer? { - delegate?.navigationMapView?(mapView, waypointStyleLayerWithIdentifier: identifier, source: source) + self.delegate?.navigationMapView?(mapView, waypointStyleLayerWithIdentifier: identifier, source: source) } func navigationMapView(_ mapView: NavigationMapView, waypointSymbolStyleLayerWithIdentifier identifier: String, source: MLNSource) -> MLNStyleLayer? { - delegate?.navigationMapView?(mapView, waypointSymbolStyleLayerWithIdentifier: identifier, source: source) + self.delegate?.navigationMapView?(mapView, waypointSymbolStyleLayerWithIdentifier: identifier, source: source) } func navigationMapView(_ mapView: NavigationMapView, shapeFor waypoints: [Waypoint], legIndex: Int) -> MLNShape? { - delegate?.navigationMapView?(mapView, shapeFor: waypoints, legIndex: legIndex) + self.delegate?.navigationMapView?(mapView, shapeFor: waypoints, legIndex: legIndex) } func navigationMapView(_ mapView: NavigationMapView, shapeFor routes: [Route]) -> MLNShape? { - delegate?.navigationMapView?(mapView, shapeFor: routes) + self.delegate?.navigationMapView?(mapView, shapeFor: routes) } func navigationMapView(_ mapView: NavigationMapView, didSelect route: Route) { - delegate?.navigationMapView?(mapView, didSelect: route) + self.delegate?.navigationMapView?(mapView, didSelect: route) } func navigationMapView(_ mapView: NavigationMapView, simplifiedShapeFor route: Route) -> MLNShape? { - delegate?.navigationMapView?(mapView, simplifiedShapeFor: route) + self.delegate?.navigationMapView?(mapView, simplifiedShapeFor: route) } func navigationMapView(_ mapView: MLNMapView, imageFor annotation: MLNAnnotation) -> MLNAnnotationImage? { - delegate?.navigationMapView?(mapView, imageFor: annotation) + self.delegate?.navigationMapView?(mapView, imageFor: annotation) } func navigationMapView(_ mapView: MLNMapView, viewFor annotation: MLNAnnotation) -> MLNAnnotationView? { - delegate?.navigationMapView?(mapView, viewFor: annotation) + self.delegate?.navigationMapView?(mapView, viewFor: annotation) } func navigationMapViewUserAnchorPoint(_ mapView: NavigationMapView) -> CGPoint { // If the end of route component is showing, then put the anchor point slightly above the middle of the map - if navigationView.endOfRouteView != nil, let show = navigationView.endOfRouteShowConstraint, show.isActive { + if self.navigationView.endOfRouteView != nil, let show = navigationView.endOfRouteShowConstraint, show.isActive { return CGPoint(x: mapView.bounds.midX, y: mapView.bounds.height * 0.4) } // otherwise, ask the delegate or return .zero - return delegate?.navigationMapViewUserAnchorPoint?(mapView) ?? .zero + return self.delegate?.navigationMapViewUserAnchorPoint?(mapView) ?? .zero } /** @@ -659,22 +659,22 @@ extension RouteMapViewController: NavigationViewDelegate { - parameter location: The user’s current location. */ func labelCurrentRoad(at rawLocation: CLLocation, for snappedLoction: CLLocation? = nil) { - guard navigationView.resumeButton.isHidden else { + guard self.navigationView.resumeButton.isHidden else { return } - let roadName = delegate?.mapViewController(self, roadNameAt: rawLocation) + let roadName = self.delegate?.mapViewController(self, roadNameAt: rawLocation) guard roadName == nil else { if let roadName { - navigationView.wayNameView.text = roadName - navigationView.wayNameView.isHidden = roadName.isEmpty + self.navigationView.wayNameView.text = roadName + self.navigationView.wayNameView.isHidden = roadName.isEmpty } return } let location = snappedLoction ?? rawLocation - labelCurrentRoadFeature(at: location) + self.labelCurrentRoadFeature(at: location) if let labelRoadNameCompletionHandler { labelRoadNameCompletionHandler(true) @@ -708,8 +708,8 @@ extension RouteMapViewController: NavigationViewDelegate { style.insertLayer(streetLabelLayer, at: 0) } - let userPuck = mapView.convert(closestCoordinate, toPointTo: mapView) - let features = mapView.visibleFeatures(at: userPuck, styleLayerIdentifiers: Set([roadLabelLayerIdentifier])) + let userPuck = self.mapView.convert(closestCoordinate, toPointTo: self.mapView) + let features = self.mapView.visibleFeatures(at: userPuck, styleLayerIdentifiers: Set([roadLabelLayerIdentifier])) var smallestLabelDistance = Double.infinity var currentName: String? var currentShieldName: NSAttributedString? @@ -741,11 +741,11 @@ extension RouteMapViewController: NavigationViewDelegate { smallestLabelDistance = minDistanceBetweenPoints if let line = feature as? MLNPolylineFeature { - let roadNameRecord = roadFeature(for: line) + let roadNameRecord = self.roadFeature(for: line) currentShieldName = roadNameRecord.shieldName currentName = roadNameRecord.roadName } else if let line = feature as? MLNMultiPolylineFeature { - let roadNameRecord = roadFeature(for: line) + let roadNameRecord = self.roadFeature(for: line) currentShieldName = roadNameRecord.shieldName currentName = roadNameRecord.roadName } @@ -756,30 +756,30 @@ extension RouteMapViewController: NavigationViewDelegate { let hasWayName = currentName != nil || currentShieldName != nil if smallestLabelDistance < 5, hasWayName { if let currentShieldName { - navigationView.wayNameView.attributedText = currentShieldName + self.navigationView.wayNameView.attributedText = currentShieldName } else if let currentName { - navigationView.wayNameView.text = currentName + self.navigationView.wayNameView.text = currentName } - navigationView.wayNameView.isHidden = false + self.navigationView.wayNameView.isHidden = false } else { - navigationView.wayNameView.isHidden = true + self.navigationView.wayNameView.isHidden = true } } private func roadFeature(for line: MLNPolylineFeature) -> (roadName: String?, shieldName: NSAttributedString?) { - let roadNameRecord = roadFeatureHelper(ref: line.attribute(forKey: "ref"), - shield: line.attribute(forKey: "shield"), - reflen: line.attribute(forKey: "reflen"), - name: line.attribute(forKey: "name")) + let roadNameRecord = self.roadFeatureHelper(ref: line.attribute(forKey: "ref"), + shield: line.attribute(forKey: "shield"), + reflen: line.attribute(forKey: "reflen"), + name: line.attribute(forKey: "name")) return (roadName: roadNameRecord.roadName, shieldName: roadNameRecord.shieldName) } private func roadFeature(for line: MLNMultiPolylineFeature) -> (roadName: String?, shieldName: NSAttributedString?) { - let roadNameRecord = roadFeatureHelper(ref: line.attribute(forKey: "ref"), - shield: line.attribute(forKey: "shield"), - reflen: line.attribute(forKey: "reflen"), - name: line.attribute(forKey: "name")) + let roadNameRecord = self.roadFeatureHelper(ref: line.attribute(forKey: "ref"), + shield: line.attribute(forKey: "shield"), + reflen: line.attribute(forKey: "reflen"), + name: line.attribute(forKey: "name")) return (roadName: roadNameRecord.roadName, shieldName: roadNameRecord.shieldName) } @@ -788,7 +788,7 @@ extension RouteMapViewController: NavigationViewDelegate { var currentShieldName: NSAttributedString?, currentRoadName: String? if let text = ref as? String, let shieldID = shield as? String, let reflenDigit = reflen as? Int { - currentShieldName = roadShieldName(for: text, shield: shieldID, reflen: reflenDigit) + currentShieldName = self.roadShieldName(for: text, shield: shieldID, reflen: reflenDigit) } if let roadName = name as? String { @@ -820,27 +820,27 @@ extension RouteMapViewController: NavigationViewDelegate { } @objc func updateETA() { - guard isViewLoaded, routeController != nil else { return } - navigationView.bottomBannerView.updateETA(routeProgress: routeController.routeProgress) + guard isViewLoaded, self.routeController != nil else { return } + self.navigationView.bottomBannerView.updateETA(routeProgress: self.routeController.routeProgress) } func resetETATimer() { - removeTimer() - updateETATimer = Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(updateETA), userInfo: nil, repeats: true) + self.removeTimer() + self.updateETATimer = Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(self.updateETA), userInfo: nil, repeats: true) } func showRouteIfNeeded() { guard isViewLoaded, view.window != nil else { return } - guard !mapView.showsRoute else { return } - mapView.showRoutes([routeController.routeProgress.route], legIndex: routeController.routeProgress.legIndex) - mapView.showWaypoints(routeController.routeProgress.route, legIndex: routeController.routeProgress.legIndex) + guard !self.mapView.showsRoute else { return } + self.mapView.showRoutes([self.routeController.routeProgress.route], legIndex: self.routeController.routeProgress.legIndex) + self.mapView.showWaypoints(self.routeController.routeProgress.route, legIndex: self.routeController.routeProgress.legIndex) - if routeController.routeProgress.currentLegProgress.stepIndex + 1 <= routeController.routeProgress.currentLegProgress.leg.steps.count { - mapView.addArrow(route: routeController.routeProgress.route, legIndex: routeController.routeProgress.legIndex, stepIndex: routeController.routeProgress.currentLegProgress.stepIndex + 1) + if self.routeController.routeProgress.currentLegProgress.stepIndex + 1 <= self.routeController.routeProgress.currentLegProgress.leg.steps.count { + self.mapView.addArrow(route: self.routeController.routeProgress.route, legIndex: self.routeController.routeProgress.legIndex, stepIndex: self.routeController.routeProgress.currentLegProgress.stepIndex + 1) } - if annotatesSpokenInstructions { - mapView.showVoiceInstructionsOnMap(route: routeController.routeProgress.route) + if self.annotatesSpokenInstructions { + self.mapView.showVoiceInstructionsOnMap(route: self.routeController.routeProgress.route) } } } @@ -858,16 +858,16 @@ extension RouteMapViewController: StepsViewControllerDelegate { self.stepsViewController = nil } - mapView.enableFrameByFrameCourseViewTracking(for: 1) - mapView.tracksUserCourse = false - mapView.setCenter(upcomingStep.maneuverLocation, zoomLevel: mapView.zoomLevel, direction: upcomingStep.initialHeading!, animated: true, completionHandler: nil) + self.mapView.enableFrameByFrameCourseViewTracking(for: 1) + self.mapView.tracksUserCourse = false + self.mapView.setCenter(upcomingStep.maneuverLocation, zoomLevel: self.mapView.zoomLevel, direction: upcomingStep.initialHeading!, animated: true, completionHandler: nil) guard isViewLoaded, view.window != nil else { return } - mapView.addArrow(route: routeController.routeProgress.route, legIndex: legIndex, stepIndex: stepIndex + 1) + self.mapView.addArrow(route: self.routeController.routeProgress.route, legIndex: legIndex, stepIndex: stepIndex + 1) } func addPreviewInstructions(step: RouteStep, maneuverStep: RouteStep, distance: CLLocationDistance?) { - removePreviewInstructions() + self.removePreviewInstructions() guard let instructions = step.instructionsDisplayedAlongStep?.last else { return } @@ -876,11 +876,11 @@ extension RouteMapViewController: StepsViewControllerDelegate { instructionsView.delegate = self instructionsView.distance = distance - navigationView.instructionsBannerContentView.backgroundColor = instructionsView.backgroundColor + self.navigationView.instructionsBannerContentView.backgroundColor = instructionsView.backgroundColor view.addSubview(instructionsView) instructionsView.update(for: instructions) - previewInstructionsView = instructionsView + self.previewInstructionsView = instructionsView } func didDismissStepsViewController(_ viewController: StepsViewController) { @@ -893,7 +893,7 @@ extension RouteMapViewController: StepsViewControllerDelegate { func statusView(_ statusView: StatusView, valueChangedTo value: Double) { let displayValue = 1 + min(Int(9 * value), 8) let title = String.Localized.simulationStatus(speed: displayValue) - showStatus(title: title, for: .infinity, interactive: true) + self.showStatus(title: title, for: .infinity, interactive: true) if let locationManager = routeController.locationManager as? SimulatedLocationManager { locationManager.speedMultiplier = Double(displayValue) @@ -915,7 +915,7 @@ private extension RouteMapViewController { } @objc func keyboardWillShow(notification: NSNotification) { - guard navigationView.endOfRouteView != nil else { return } + guard self.navigationView.endOfRouteView != nil else { return } guard let userInfo = notification.userInfo else { return } guard let curveValue = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? Int else { return } guard let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else { return } @@ -928,7 +928,7 @@ private extension RouteMapViewController { if #available(iOS 11.0, *) { navigationView.endOfRouteShowConstraint?.constant = -1 * (keyboardHeight - view.safeAreaInsets.bottom) // subtract the safe area, which is part of the keyboard's frame } else { - navigationView.endOfRouteShowConstraint?.constant = -1 * keyboardHeight + self.navigationView.endOfRouteShowConstraint?.constant = -1 * keyboardHeight } let opts = UIView.AnimationOptions(curve: options.curve) @@ -936,13 +936,13 @@ private extension RouteMapViewController { } @objc func keyboardWillHide(notification: NSNotification) { - guard navigationView.endOfRouteView != nil else { return } + guard self.navigationView.endOfRouteView != nil else { return } guard let userInfo = notification.userInfo else { return } let curve = UIView.AnimationCurve(rawValue: userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as! Int) let options = (duration: userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! Double, curve: UIView.AnimationOptions(curve: curve!)) - navigationView.endOfRouteShowConstraint?.constant = 0 + self.navigationView.endOfRouteShowConstraint?.constant = 0 UIView.animate(withDuration: options.duration, delay: 0, options: options.curve, animations: view.layoutIfNeeded, completion: nil) } diff --git a/MapboxNavigation/RouteVoiceController.swift b/MapboxNavigation/RouteVoiceController.swift index 674d2afd..121be56d 100644 --- a/MapboxNavigation/RouteVoiceController.swift +++ b/MapboxNavigation/RouteVoiceController.swift @@ -86,11 +86,11 @@ open class RouteVoiceController: NSObject, AVSpeechSynthesizerDelegate { override public init() { super.init() - verifyBackgroundAudio() + self.verifyBackgroundAudio() - speechSynth.delegate = self + self.speechSynth.delegate = self - resumeNotifications() + self.resumeNotifications() } private func verifyBackgroundAudio() { @@ -109,11 +109,11 @@ open class RouteVoiceController: NSObject, AVSpeechSynthesizerDelegate { } func resumeNotifications() { - NotificationCenter.default.addObserver(self, selector: #selector(didPassSpokenInstructionPoint(notification:)), name: .routeControllerDidPassSpokenInstructionPoint, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(pauseSpeechAndPlayReroutingDing(notification:)), name: .routeControllerWillReroute, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(didReroute(notification:)), name: .routeControllerDidReroute, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(self.didPassSpokenInstructionPoint(notification:)), name: .routeControllerDidPassSpokenInstructionPoint, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(self.pauseSpeechAndPlayReroutingDing(notification:)), name: .routeControllerWillReroute, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(self.didReroute(notification:)), name: .routeControllerDidReroute, object: nil) - muteToken = NavigationSettings.shared.observe(\.voiceMuted) { [weak self] settings, _ in + self.muteToken = NavigationSettings.shared.observe(\.voiceMuted) { [weak self] settings, _ in if settings.voiceMuted { self?.speechSynth.stopSpeaking(at: .immediate) } @@ -129,30 +129,30 @@ open class RouteVoiceController: NSObject, AVSpeechSynthesizerDelegate { @objc func didReroute(notification: NSNotification) { // Play reroute sound when a faster route is found if notification.userInfo?[RouteControllerNotificationUserInfoKey.isProactiveKey] as! Bool { - pauseSpeechAndPlayReroutingDing(notification: notification) + self.pauseSpeechAndPlayReroutingDing(notification: notification) } } @objc func pauseSpeechAndPlayReroutingDing(notification: NSNotification) { - speechSynth.stopSpeaking(at: .word) + self.speechSynth.stopSpeaking(at: .word) - guard playRerouteSound, !NavigationSettings.shared.voiceMuted else { + guard self.playRerouteSound, !NavigationSettings.shared.voiceMuted else { return } do { - try mixAudio() + try self.mixAudio() } catch { - voiceControllerDelegate?.voiceController?(self, spokenInstructionsDidFailWith: error) + self.voiceControllerDelegate?.voiceController?(self, spokenInstructionsDidFailWith: error) } - rerouteSoundPlayer.play() + self.rerouteSoundPlayer.play() } @objc public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) { do { - try unDuckAudio() + try self.unDuckAudio() } catch { - voiceControllerDelegate?.voiceController?(self, spokenInstructionsDidFailWith: error) + self.voiceControllerDelegate?.voiceController?(self, spokenInstructionsDidFailWith: error) } } @@ -175,14 +175,14 @@ open class RouteVoiceController: NSObject, AVSpeechSynthesizerDelegate { @objc open func didPassSpokenInstructionPoint(notification: NSNotification) { guard !NavigationSettings.shared.voiceMuted else { return } - routeProgress = notification.userInfo?[RouteControllerNotificationUserInfoKey.routeProgressKey] as? RouteProgress - assert(routeProgress != nil, "routeProgress should not be nil.") + self.routeProgress = notification.userInfo?[RouteControllerNotificationUserInfoKey.routeProgressKey] as? RouteProgress + assert(self.routeProgress != nil, "routeProgress should not be nil.") guard let instruction = routeProgress?.currentLegProgress.currentStepProgress.currentSpokenInstruction else { return } - let speechLocale = routeProgress?.route.routeOptions.locale + let speechLocale = self.routeProgress?.route.routeOptions.locale - lastSpokenInstruction = instruction - speak(instruction, with: speechLocale) + self.lastSpokenInstruction = instruction + self.speak(instruction, with: speechLocale) } /** @@ -193,17 +193,17 @@ open class RouteVoiceController: NSObject, AVSpeechSynthesizerDelegate { - parameter ignoreProgress: A `Bool` that indicates if the routeProgress is added to the instruction. */ open func speak(_ instruction: SpokenInstruction, with locale: Locale?, ignoreProgress: Bool = false) { - if speechSynth.isSpeaking, let lastSpokenInstruction { - voiceControllerDelegate?.voiceController?(self, didInterrupt: lastSpokenInstruction, with: instruction) + if self.speechSynth.isSpeaking, let lastSpokenInstruction { + self.voiceControllerDelegate?.voiceController?(self, didInterrupt: lastSpokenInstruction, with: instruction) } do { - try duckAudio() + try self.duckAudio() } catch { - voiceControllerDelegate?.voiceController?(self, spokenInstructionsDidFailWith: error) + self.voiceControllerDelegate?.voiceController?(self, spokenInstructionsDidFailWith: error) } - let modifiedInstruction = voiceControllerDelegate?.voiceController?(self, willSpeak: instruction, routeProgress: routeProgress) ?? instruction + let modifiedInstruction = self.voiceControllerDelegate?.voiceController?(self, willSpeak: instruction, routeProgress: self.routeProgress) ?? instruction let utterance: AVSpeechUtterance @@ -222,7 +222,7 @@ open class RouteVoiceController: NSObject, AVSpeechSynthesizerDelegate { utterance.voice = AVSpeechSynthesisVoice(language: locale?.identifier ?? Locale.preferredLocalLanguageCountryCode) } - speechSynth.speak(utterance) + self.speechSynth.speak(utterance) } } diff --git a/MapboxNavigation/StatusView.swift b/MapboxNavigation/StatusView.swift index ec4c6c44..2f01501d 100644 --- a/MapboxNavigation/StatusView.swift +++ b/MapboxNavigation/StatusView.swift @@ -23,18 +23,18 @@ public class StatusView: UIView { @objc public var canChangeValue = false var value: Double = 0 { didSet { - delegate?.statusView?(self, valueChangedTo: value) + self.delegate?.statusView?(self, valueChangedTo: self.value) } } @objc override public init(frame: CGRect) { super.init(frame: frame) - commonInit() + self.commonInit() } @objc public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) - commonInit() + self.commonInit() } func commonInit() { @@ -73,22 +73,22 @@ public class StatusView: UIView { } @objc func pan(_ sender: UIPanGestureRecognizer) { - guard canChangeValue else { return } + guard self.canChangeValue else { return } let location = sender.location(in: self) if sender.state == .began { - panStartPoint = location + self.panStartPoint = location } else if sender.state == .changed { guard let startPoint = panStartPoint else { return } let offsetX = location.x - startPoint.x let coefficient = (offsetX / bounds.width) / 20.0 - value = Double(min(max(CGFloat(value) + coefficient, 0), 1)) + self.value = Double(min(max(CGFloat(self.value) + coefficient, 0), 1)) } } @objc func tap(_ sender: UITapGestureRecognizer) { - guard canChangeValue else { return } + guard self.canChangeValue else { return } let location = sender.location(in: self) @@ -102,7 +102,7 @@ public class StatusView: UIView { @unknown default: fatalError("Unknown userInterfaceLayoutDirection") } - value = min(max(value + incrementer, 0), 1) + self.value = min(max(self.value + incrementer, 0), 1) } } @@ -110,12 +110,12 @@ public class StatusView: UIView { Shows the status view with an optional spinner. */ public func show(_ title: String, showSpinner: Bool, interactive: Bool = false) { - canChangeValue = interactive - textLabel.text = title - activityIndicatorView.hidesWhenStopped = true - if !showSpinner { activityIndicatorView.stopAnimating() } + self.canChangeValue = interactive + self.textLabel.text = title + self.activityIndicatorView.hidesWhenStopped = true + if !showSpinner { self.activityIndicatorView.stopAnimating() } - guard isCurrentlyVisible == false, isHidden == true else { return } + guard self.isCurrentlyVisible == false, isHidden == true else { return } let show = { self.isHidden = false diff --git a/MapboxNavigation/StepsViewController.swift b/MapboxNavigation/StepsViewController.swift index 17209575..53977b65 100644 --- a/MapboxNavigation/StepsViewController.swift +++ b/MapboxNavigation/StepsViewController.swift @@ -54,15 +54,15 @@ public class StepsViewController: UIViewController { @discardableResult func rebuildDataSourceIfNecessary() -> Bool { - let legIndex = routeProgress.legIndex - let stepIndex = routeProgress.currentLegProgress.stepIndex - let didProcessCurrentStep = previousLegIndex == legIndex && previousStepIndex == stepIndex + let legIndex = self.routeProgress.legIndex + let stepIndex = self.routeProgress.currentLegProgress.stepIndex + let didProcessCurrentStep = self.previousLegIndex == legIndex && self.previousStepIndex == stepIndex guard !didProcessCurrentStep else { return false } - sections.removeAll() + self.sections.removeAll() - let currentLeg = routeProgress.currentLeg + let currentLeg = self.routeProgress.currentLeg // Add remaining steps for current leg var section = [RouteStep]() @@ -74,29 +74,29 @@ public class StepsViewController: UIViewController { } if !section.isEmpty { - sections.append(section) + self.sections.append(section) } // Include all steps on any future legs - if !routeProgress.isFinalLeg { - for item in routeProgress.route.legs.suffix(from: routeProgress.legIndex + 1) { + if !self.routeProgress.isFinalLeg { + for item in self.routeProgress.route.legs.suffix(from: self.routeProgress.legIndex + 1) { var steps = item.steps // Don't include the last step, it includes nothing _ = steps.popLast() - sections.append(steps) + self.sections.append(steps) } } - previousStepIndex = stepIndex - previousLegIndex = legIndex + self.previousStepIndex = stepIndex + self.previousLegIndex = legIndex return true } override open func viewDidLoad() { super.viewDidLoad() - setupViews() - rebuildDataSourceIfNecessary() + self.setupViews() + self.rebuildDataSourceIfNecessary() NotificationCenter.default.addObserver(self, selector: #selector(StepsViewController.progressDidChange(_:)), name: .routeControllerProgressDidChange, object: nil) } @@ -106,8 +106,8 @@ public class StepsViewController: UIViewController { } @objc func progressDidChange(_ notification: Notification) { - if rebuildDataSourceIfNecessary() { - tableView.reloadData() + if self.rebuildDataSourceIfNecessary() { + self.tableView.reloadData() } } @@ -173,7 +173,7 @@ public class StepsViewController: UIViewController { tableView.bottomAnchor.constraint(equalTo: dismissButton.topAnchor).isActive = true tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true - tableView.register(StepTableViewCell.self, forCellReuseIdentifier: cellId) + tableView.register(StepTableViewCell.self, forCellReuseIdentifier: self.cellId) } /** @@ -205,14 +205,14 @@ public class StepsViewController: UIViewController { } @IBAction func tappedDismiss(_ sender: Any) { - delegate?.didDismissStepsViewController(self) + self.delegate?.didDismissStepsViewController(self) } /** Dismisses the `StepsViewController`. */ public func dismiss(completion: CompletionHandler? = nil) { - slideUpAnimation { + self.slideUpAnimation { self.willMove(toParent: nil) self.view.removeFromSuperview() self.removeFromParent() @@ -231,21 +231,21 @@ extension StepsViewController: UITableViewDelegate { if indexPath.section > 0 { stepIndex = indexPath.row } else { - stepIndex = indexPath.row + routeProgress.currentLegProgress.stepIndex + stepIndex = indexPath.row + self.routeProgress.currentLegProgress.stepIndex // For the current leg, we need to know the upcoming step. - stepIndex += indexPath.row + 1 > sections[indexPath.section].count ? 0 : 1 + stepIndex += indexPath.row + 1 > self.sections[indexPath.section].count ? 0 : 1 } - delegate?.stepsViewController?(self, didSelect: indexPath.section, stepIndex: stepIndex, cell: cell) + self.delegate?.stepsViewController?(self, didSelect: indexPath.section, stepIndex: stepIndex, cell: cell) } } extension StepsViewController: UITableViewDataSource { public func numberOfSections(in tableView: UITableView) -> Int { - sections.count + self.sections.count } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - let steps = sections[section] + let steps = self.sections[section] return steps.count } @@ -254,19 +254,19 @@ extension StepsViewController: UITableViewDataSource { } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { - let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! StepTableViewCell + let cell = tableView.dequeueReusableCell(withIdentifier: self.cellId, for: indexPath) as! StepTableViewCell return cell } public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { - updateCell(cell as! StepTableViewCell, at: indexPath) + self.updateCell(cell as! StepTableViewCell, at: indexPath) } func updateCell(_ cell: StepTableViewCell, at indexPath: IndexPath) { cell.instructionsView.primaryLabel.viewForAvailableBoundsCalculation = cell cell.instructionsView.secondaryLabel.viewForAvailableBoundsCalculation = cell - let step = sections[indexPath.section][indexPath.row] + let step = self.sections[indexPath.section][indexPath.row] if let instructions = step.instructionsDisplayedAlongStep?.last { cell.instructionsView.update(for: instructions) @@ -277,7 +277,7 @@ extension StepsViewController: UITableViewDataSource { cell.instructionsView.stepListIndicatorView.isHidden = true // Hide cell separator if it’s the last row in a section - let isLastRowInSection = indexPath.row == sections[indexPath.section].count - 1 + let isLastRowInSection = indexPath.row == self.sections[indexPath.section].count - 1 cell.separatorView.isHidden = isLastRowInSection } @@ -286,7 +286,7 @@ extension StepsViewController: UITableViewDataSource { return nil } - let leg = routeProgress.route.legs[section] + let leg = self.routeProgress.route.legs[section] let sourceName = leg.source.name let destinationName = leg.destination.name let majorWays = leg.name.components(separatedBy: ", ") @@ -314,12 +314,12 @@ open class StepTableViewCell: UITableViewCell { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) - commonInit() + self.commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) - commonInit() + self.commonInit() } func commonInit() { @@ -350,7 +350,7 @@ open class StepTableViewCell: UITableViewCell { override open func prepareForReuse() { super.prepareForReuse() - instructionsView.update(for: nil) + self.instructionsView.update(for: nil) } } diff --git a/MapboxNavigation/Style.swift b/MapboxNavigation/Style.swift index 5061f29e..5d816a23 100644 --- a/MapboxNavigation/Style.swift +++ b/MapboxNavigation/Style.swift @@ -94,12 +94,12 @@ open class FloatingButton: Button { var constrainedSize: CGSize? { didSet { guard let size = constrainedSize else { - NSLayoutConstraint.deactivate([widthConstraint, heightConstraint]) + NSLayoutConstraint.deactivate([self.widthConstraint, self.heightConstraint]) return } - widthConstraint.constant = size.width - heightConstraint.constant = size.height - NSLayoutConstraint.activate([widthConstraint, heightConstraint]) + self.widthConstraint.constant = size.width + self.heightConstraint.constant = size.height + NSLayoutConstraint.activate([self.widthConstraint, self.heightConstraint]) } } @@ -124,12 +124,12 @@ public class ReportButton: Button { public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) - commonInit() + self.commonInit() } override public init(frame: CGRect) { super.init(frame: frame) - commonInit() + self.commonInit() } private func commonInit() { @@ -156,7 +156,7 @@ public class ReportButton: Button { } @objc func slideUp(constraint: NSLayoutConstraint) { - constraint.constant = upConstant + constraint.constant = self.upConstant setNeedsUpdateConstraints() UIView.defaultSpringAnimation(0.5, animations: { self.superview?.layoutIfNeeded() @@ -180,8 +180,8 @@ public class HighlightedButton: Button {} public class ResumeButton: UIControl { override public dynamic var tintColor: UIColor! { didSet { - imageView.tintColor = tintColor - titleLabel.textColor = tintColor + self.imageView.tintColor = self.tintColor + self.titleLabel.textColor = self.tintColor } } @@ -190,27 +190,27 @@ public class ResumeButton: UIControl { override public init(frame: CGRect) { super.init(frame: frame) - commonInit() + self.commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) - commonInit() + self.commonInit() } override public func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() - commonInit() + self.commonInit() } func commonInit() { - titleLabel.text = NSLocalizedString("RESUME", bundle: .mapboxNavigation, value: "Resume", comment: "Button title for resume tracking") - titleLabel.sizeToFit() - addSubview(imageView) - addSubview(titleLabel) + self.titleLabel.text = NSLocalizedString("RESUME", bundle: .mapboxNavigation, value: "Resume", comment: "Button title for resume tracking") + self.titleLabel.sizeToFit() + addSubview(self.imageView) + addSubview(self.titleLabel) - titleLabel.translatesAutoresizingMaskIntoConstraints = false - imageView.translatesAutoresizingMaskIntoConstraints = false + self.titleLabel.translatesAutoresizingMaskIntoConstraints = false + self.imageView.translatesAutoresizingMaskIntoConstraints = false translatesAutoresizingMaskIntoConstraints = false let views = ["label": titleLabel, "imageView": imageView] @@ -240,8 +240,8 @@ open class StepListIndicatorView: UIView { layer.cornerRadius = bounds.midY layer.masksToBounds = true layer.opacity = 0.25 - applyGradient(colors: gradientColors) - addBlurredEffect(view: blurredEffectView, to: self) + applyGradient(colors: self.gradientColors) + self.addBlurredEffect(view: self.blurredEffectView, to: self) } fileprivate func addBlurredEffect(view: UIView, to parentView: UIView) { @@ -257,13 +257,13 @@ open class StylableLabel: UILabel { // Workaround the fact that UILabel properties are not marked with UI_APPEARANCE_SELECTOR @objc open dynamic var normalTextColor: UIColor = .black { didSet { - textColor = normalTextColor + textColor = self.normalTextColor } } @objc open dynamic var normalFont: UIFont = .systemFont(ofSize: 16) { didSet { - font = normalFont + font = self.normalFont } } } @@ -273,13 +273,13 @@ open class StylableLabel: UILabel { open class StylableView: UIView { @objc dynamic var borderWidth: CGFloat = 0.0 { didSet { - layer.borderWidth = borderWidth + layer.borderWidth = self.borderWidth } } @objc dynamic var cornerRadius: CGFloat = 0.0 { didSet { - layer.cornerRadius = cornerRadius + layer.cornerRadius = self.cornerRadius } } } @@ -290,7 +290,7 @@ open class StylableTextView: UITextView { // Workaround the fact that UITextView properties are not marked with UI_APPEARANCE_SELECTOR @objc open dynamic var normalTextColor: UIColor = .black { didSet { - textColor = normalTextColor + textColor = self.normalTextColor } } } @@ -307,11 +307,11 @@ open class DistanceLabel: StylableLabel { } @objc public dynamic var valueFont: UIFont = .systemFont(ofSize: 16, weight: .medium) { - didSet { update() } + didSet { self.update() } } @objc public dynamic var unitFont: UIFont = .systemFont(ofSize: 11, weight: .medium) { - didSet { update() } + didSet { self.update() } } /** @@ -322,7 +322,7 @@ open class DistanceLabel: StylableLabel { */ var attributedDistanceString: NSAttributedString? { didSet { - update() + self.update() } } @@ -339,19 +339,19 @@ open class DistanceLabel: StylableLabel { let foregroundColor: UIColor let font: UIFont if emphasizedDistanceString.attribute(NSAttributedString.Key.quantity, at: range.location, effectiveRange: nil) != nil { - foregroundColor = valueTextColor - font = valueFont + foregroundColor = self.valueTextColor + font = self.valueFont hasQuantity = true } else { - foregroundColor = unitTextColor - font = unitFont + foregroundColor = self.unitTextColor + font = self.unitFont } emphasizedDistanceString.addAttributes([.foregroundColor: foregroundColor, .font: font], range: range) } // As a failsafe, if no quantity was found, emphasize the entire string. if !hasQuantity { - emphasizedDistanceString.addAttributes([.foregroundColor: valueTextColor, .font: valueFont], range: wholeRange) + emphasizedDistanceString.addAttributes([.foregroundColor: self.valueTextColor, .font: self.valueFont], range: wholeRange) } // Replace spaces with hair spaces to economize on horizontal screen @@ -417,19 +417,19 @@ open class WayNameView: UIView { var text: String? { get { - label.text + self.label.text } set { - label.text = newValue + self.label.text = newValue } } var attributedText: NSAttributedString? { get { - label.attributedText + self.label.attributedText } set { - label.attributedText = newValue + self.label.attributedText = newValue } } @@ -445,18 +445,18 @@ open class WayNameView: UIView { override public init(frame: CGRect) { super.init(frame: frame) - commonInit() + self.commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) - commonInit() + self.commonInit() } func commonInit() { - addSubview(label) + addSubview(self.label) layoutMargins = WayNameView.textInsets - label.pinInSuperview(respectingMargins: true) + self.label.pinInSuperview(respectingMargins: true) } override open func layoutSubviews() { @@ -486,13 +486,13 @@ public class ProgressBar: UIView { // Set the progress between 0.0-1.0 var progress: CGFloat = 0 { didSet { - updateProgressBar() + self.updateProgressBar() layoutIfNeeded() } } override open var description: String { - super.description + "; progress = \(progress)" + super.description + "; progress = \(self.progress)" } func setProgress(_ progress: CGFloat, animated: Bool) { @@ -504,11 +504,11 @@ public class ProgressBar: UIView { override public func layoutSubviews() { super.layoutSubviews() - if bar.superview == nil { - addSubview(bar) + if self.bar.superview == nil { + addSubview(self.bar) } - updateProgressBar() + self.updateProgressBar() } func updateProgressBar() { @@ -518,11 +518,11 @@ public class ProgressBar: UIView { case .leftToRight: origin = .zero case .rightToLeft: - origin = CGPoint(x: superview.bounds.width * (1 - progress), y: 0) + origin = CGPoint(x: superview.bounds.width * (1 - self.progress), y: 0) @unknown default: fatalError("Unknown userInterfaceLayoutDirection") } - bar.frame = CGRect(origin: origin, size: CGSize(width: superview.bounds.width * progress, height: bounds.height)) + self.bar.frame = CGRect(origin: origin, size: CGSize(width: superview.bounds.width * self.progress, height: bounds.height)) } } } @@ -549,35 +549,35 @@ open class StylableButton: UIButton { // Sets the font on the button’s titleLabel @objc open dynamic var textFont: UIFont = .systemFont(ofSize: 20, weight: .medium) { didSet { - titleLabel?.font = textFont + titleLabel?.font = self.textFont } } // Sets the text color for normal state @objc open dynamic var textColor: UIColor = .black { didSet { - setTitleColor(textColor, for: .normal) + setTitleColor(self.textColor, for: .normal) } } // Sets the border color @objc open dynamic var borderColor: UIColor = .clear { didSet { - layer.borderColor = borderColor.cgColor + layer.borderColor = self.borderColor.cgColor } } // Sets the border width @objc open dynamic var borderWidth: CGFloat = 0 { didSet { - layer.borderWidth = borderWidth + layer.borderWidth = self.borderWidth } } // Sets the corner radius @objc open dynamic var cornerRadius: CGFloat = 0 { didSet { - layer.cornerRadius = cornerRadius + layer.cornerRadius = self.cornerRadius } } } @@ -589,7 +589,7 @@ open class ManeuverContainerView: UIView { @objc dynamic var height: CGFloat = 100 { didSet { - heightConstraint.constant = height + self.heightConstraint.constant = self.height setNeedsUpdateConstraints() } } @@ -645,6 +645,6 @@ public class MarkerView: UIView { override public func draw(_ rect: CGRect) { super.draw(rect) - StyleKitMarker.drawMarker(innerColor: innerColor, shadowColor: shadowColor, pinColor: pinColor, strokeColor: strokeColor) + StyleKitMarker.drawMarker(innerColor: self.innerColor, shadowColor: self.shadowColor, pinColor: self.pinColor, strokeColor: self.strokeColor) } } diff --git a/MapboxNavigation/StyleManager.swift b/MapboxNavigation/StyleManager.swift index ce5ee647..5e83c62c 100644 --- a/MapboxNavigation/StyleManager.swift +++ b/MapboxNavigation/StyleManager.swift @@ -41,7 +41,7 @@ open class StyleManager: NSObject { */ @objc public var automaticallyAdjustsStyleForTimeOfDay = true { didSet { - resetTimeOfDayTimer() + self.resetTimeOfDayTimer() } } @@ -55,8 +55,8 @@ open class StyleManager: NSObject { */ @objc public var styles = [Style]() { didSet { - applyStyle() - resetTimeOfDayTimer() + self.applyStyle() + self.resetTimeOfDayTimer() } } @@ -72,8 +72,8 @@ open class StyleManager: NSObject { public required init(_ delegate: StyleManagerDelegate) { self.delegate = delegate super.init() - resumeNotifications() - resetTimeOfDayTimer() + self.resumeNotifications() + self.resetTimeOfDayTimer() } deinit { @@ -82,8 +82,8 @@ open class StyleManager: NSObject { } func resumeNotifications() { - NotificationCenter.default.addObserver(self, selector: #selector(timeOfDayChanged), name: UIApplication.significantTimeChangeNotification, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(preferredContentSizeChanged(_:)), name: UIContentSizeCategory.didChangeNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(self.timeOfDayChanged), name: UIApplication.significantTimeChangeNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(self.preferredContentSizeChanged(_:)), name: UIContentSizeCategory.didChangeNotification, object: nil) } func suspendNotifications() { @@ -92,9 +92,9 @@ open class StyleManager: NSObject { } func resetTimeOfDayTimer() { - NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(timeOfDayChanged), object: nil) + NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.timeOfDayChanged), object: nil) - guard automaticallyAdjustsStyleForTimeOfDay, styles.count > 1 else { return } + guard self.automaticallyAdjustsStyleForTimeOfDay, self.styles.count > 1 else { return } guard let location = delegate?.locationFor(styleManager: self) else { return } guard let solar = Solar(date: date, coordinate: location.coordinate), @@ -108,55 +108,55 @@ open class StyleManager: NSObject { return } - perform(#selector(timeOfDayChanged), with: nil, afterDelay: interval + 1) + perform(#selector(self.timeOfDayChanged), with: nil, afterDelay: interval + 1) } @objc func preferredContentSizeChanged(_ notification: Notification) { - applyStyle() + self.applyStyle() } @objc func timeOfDayChanged() { - forceRefreshAppearanceIfNeeded() - resetTimeOfDayTimer() + self.forceRefreshAppearanceIfNeeded() + self.resetTimeOfDayTimer() } func applyStyle(type styleType: StyleType) { - guard currentStyleType != styleType else { return } + guard self.currentStyleType != styleType else { return } - NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(timeOfDayChanged), object: nil) + NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.timeOfDayChanged), object: nil) - for style in styles where style.styleType == styleType { + for style in self.styles where style.styleType == styleType { style.apply() currentStyleType = styleType delegate?.styleManager?(self, didApply: style) } - forceRefreshAppearance() + self.forceRefreshAppearance() } func applyStyle() { guard let location = delegate?.locationFor(styleManager: self) else { // We can't calculate sunset or sunrise w/o a location so just apply the first style if let style = styles.first, currentStyleType != style.styleType { - currentStyleType = style.styleType + self.currentStyleType = style.styleType style.apply() - delegate?.styleManager?(self, didApply: style) + self.delegate?.styleManager?(self, didApply: style) } return } // Single style usage - guard styles.count > 1 else { + guard self.styles.count > 1 else { if let style = styles.first, currentStyleType != style.styleType { - currentStyleType = style.styleType + self.currentStyleType = style.styleType style.apply() - delegate?.styleManager?(self, didApply: style) + self.delegate?.styleManager?(self, didApply: style) } return } - let styleTypeForTimeOfDay = styleType(for: location) - applyStyle(type: styleTypeForTimeOfDay) + let styleTypeForTimeOfDay = self.styleType(for: location) + self.applyStyle(type: styleTypeForTimeOfDay) } func styleType(for location: CLLocation) -> StyleType { @@ -172,18 +172,18 @@ open class StyleManager: NSObject { func forceRefreshAppearanceIfNeeded() { guard let location = delegate?.locationFor(styleManager: self) else { return } - let styleTypeForLocation = styleType(for: location) + let styleTypeForLocation = self.styleType(for: location) // If `styles` does not contain at least one style for the selected location, don't try and apply it. - let availableStyleTypesForLocation = styles.filter { $0.styleType == styleTypeForLocation } + let availableStyleTypesForLocation = self.styles.filter { $0.styleType == styleTypeForLocation } guard availableStyleTypesForLocation.count > 0 else { return } - guard currentStyleType != styleTypeForLocation else { + guard self.currentStyleType != styleTypeForLocation else { return } - applyStyle() - forceRefreshAppearance() + self.applyStyle() + self.forceRefreshAppearance() } func forceRefreshAppearance() { @@ -194,7 +194,7 @@ open class StyleManager: NSObject { } } - delegate?.styleManagerDidRefreshAppearance?(self) + self.delegate?.styleManagerDidRefreshAppearance?(self) } } @@ -206,7 +206,7 @@ extension Date { return nil } - if isNighttime(sunrise: sunrise, sunset: sunset) { + if self.isNighttime(sunrise: sunrise, sunset: sunset) { let sunriseComponents = calendar.dateComponents([.hour, .minute, .second], from: sunrise) guard let sunriseDate = calendar.date(from: sunriseComponents) else { return nil diff --git a/MapboxNavigation/Transitioning.swift b/MapboxNavigation/Transitioning.swift index f73f9041..53d42b2a 100644 --- a/MapboxNavigation/Transitioning.swift +++ b/MapboxNavigation/Transitioning.swift @@ -20,7 +20,7 @@ extension DismissAnimator: UIViewControllerAnimatedTransitioning { let height = fromVC.view.bounds.height - toVC.view.frame.minY let finalFrame = CGRect(origin: point, size: CGSize(width: fromVC.view.bounds.width, height: height)) - UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: [.curveEaseInOut], animations: { + UIView.animate(withDuration: self.transitionDuration(using: transitionContext), delay: 0, options: [.curveEaseInOut], animations: { fromVC.view.frame = finalFrame containerView.backgroundColor = .clear }, completion: { _ in @@ -56,7 +56,7 @@ extension PresentAnimator: UIViewControllerAnimatedTransitioning { let finalFrame = CGRect(origin: CGPoint(x: 0, y: fromVC.view.bounds.height - height), size: CGSize(width: fromVC.view.bounds.width, height: height)) - UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: [.curveEaseInOut], animations: { + UIView.animate(withDuration: self.transitionDuration(using: transitionContext), delay: 0, options: [.curveEaseInOut], animations: { toView.frame = finalFrame containerView.backgroundColor = UIColor.black.withAlphaComponent(0.5) }, completion: { _ in @@ -84,7 +84,7 @@ extension DismissDraggable where Self: UIViewController { private extension UIViewController { @objc func handleDismissPan(_ sender: UIPanGestureRecognizer) { - handlePan(sender) + self.handlePan(sender) } func handlePan(_ sender: UIPanGestureRecognizer) { diff --git a/MapboxNavigation/UIFont.swift b/MapboxNavigation/UIFont.swift index 13c52b6c..60937158 100644 --- a/MapboxNavigation/UIFont.swift +++ b/MapboxNavigation/UIFont.swift @@ -23,12 +23,12 @@ extension UIFont { Returns an adjusted font for the `preferredContentSizeCategory`. */ @objc public var adjustedFont: UIFont { - let font = with(multiplier: fontSizeMultiplier) + let font = self.with(multiplier: self.fontSizeMultiplier) return font } func with(multiplier: CGFloat) -> UIFont { - let font = UIFont(descriptor: fontDescriptor, size: pointSize * fontSizeMultiplier) + let font = UIFont(descriptor: fontDescriptor, size: pointSize * self.fontSizeMultiplier) return font } diff --git a/MapboxNavigation/UIView.swift b/MapboxNavigation/UIView.swift index 29b21159..92001615 100644 --- a/MapboxNavigation/UIView.swift +++ b/MapboxNavigation/UIView.swift @@ -58,7 +58,7 @@ extension UIView { func constraints(affecting view: UIView?) -> [NSLayoutConstraint]? { guard let view else { return nil } - return constraints.filter { constraint in + return self.constraints.filter { constraint in if let first = constraint.firstItem as? UIView, first == view { return true } @@ -150,7 +150,7 @@ extension UIView { class RippleLayer: CAReplicatorLayer { var animationGroup: CAAnimationGroup? { didSet { - animationGroup?.delegate = self + self.animationGroup?.delegate = self } } @@ -163,44 +163,44 @@ class RippleLayer: CAReplicatorLayer { override init() { super.init() - commonInit() + self.commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) - commonInit() + self.commonInit() } func commonInit() { - setupRippleEffect() - repeatCount = Float(rippleRepeatCount) + self.setupRippleEffect() + repeatCount = Float(self.rippleRepeatCount) } override func layoutSublayers() { super.layoutSublayers() - rippleEffect?.bounds = CGRect(x: 0, y: 0, width: rippleRadius * 2, height: rippleRadius * 2) - rippleEffect?.cornerRadius = rippleRadius + self.rippleEffect?.bounds = CGRect(x: 0, y: 0, width: self.rippleRadius * 2, height: self.rippleRadius * 2) + self.rippleEffect?.cornerRadius = self.rippleRadius instanceCount = 3 instanceDelay = 0.4 } func setupRippleEffect() { - rippleEffect = CALayer() - rippleEffect?.borderWidth = CGFloat(rippleWidth) - rippleEffect?.borderColor = rippleColor.cgColor - rippleEffect?.opacity = 0 + self.rippleEffect = CALayer() + self.rippleEffect?.borderWidth = CGFloat(self.rippleWidth) + self.rippleEffect?.borderColor = self.rippleColor.cgColor + self.rippleEffect?.opacity = 0 - addSublayer(rippleEffect!) + addSublayer(self.rippleEffect!) } func startAnimation() { - animationGroup = rippleAnimationGroup() - rippleEffect?.add(animationGroup!, forKey: "ripple") + self.animationGroup = self.rippleAnimationGroup() + self.rippleEffect?.add(self.animationGroup!, forKey: "ripple") } func stopAnimation() { - rippleEffect?.removeAnimation(forKey: "ripple") + self.rippleEffect?.removeAnimation(forKey: "ripple") } func rippleAnimationGroup() -> CAAnimationGroup { @@ -231,7 +231,7 @@ class RippleLayer: CAReplicatorLayer { extension RippleLayer: CAAnimationDelegate { func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { if let count = rippleEffect?.animationKeys()?.count, count > 0 { - rippleEffect?.removeAllAnimations() + self.rippleEffect?.removeAllAnimations() } } } diff --git a/MapboxNavigation/UIViewController.swift b/MapboxNavigation/UIViewController.swift index 979c5d48..72ce0812 100644 --- a/MapboxNavigation/UIViewController.swift +++ b/MapboxNavigation/UIViewController.swift @@ -2,20 +2,20 @@ import UIKit extension UIViewController { func topMostViewController() -> UIViewController? { - topViewController(controller: self) + self.topViewController(controller: self) } func topViewController(controller: UIViewController? = nil) -> UIViewController? { if let navigationController = controller as? UINavigationController { - return topViewController(controller: navigationController.visibleViewController) + return self.topViewController(controller: navigationController.visibleViewController) } if let tabController = controller as? UITabBarController { if let selected = tabController.selectedViewController { - return topViewController(controller: selected) + return self.topViewController(controller: selected) } } if let presented = controller?.presentedViewController { - return topViewController(controller: presented) + return self.topViewController(controller: presented) } return controller } diff --git a/MapboxNavigation/UserCourseView.swift b/MapboxNavigation/UserCourseView.swift index 2ccf8512..2fc6c491 100644 --- a/MapboxNavigation/UserCourseView.swift +++ b/MapboxNavigation/UserCourseView.swift @@ -81,19 +81,19 @@ public class UserPuckCourseView: UIView, UserCourseView { override init(frame: CGRect) { super.init(frame: frame) - commonInit() + self.commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) - commonInit() + self.commonInit() } func commonInit() { - puckView = UserPuckStyleKitView(frame: bounds) + self.puckView = UserPuckStyleKitView(frame: bounds) backgroundColor = .clear - puckView.backgroundColor = .clear - addSubview(puckView) + self.puckView.backgroundColor = .clear + addSubview(self.puckView) } } @@ -118,7 +118,7 @@ class UserPuckStyleKitView: UIView { override func draw(_ rect: CGRect) { super.draw(rect) - drawNavigation_puck(fillColor: fillColor, puckColor: puckColor, shadowColor: shadowColor, circleColor: fillColor) + self.drawNavigation_puck(fillColor: self.fillColor, puckColor: self.puckColor, shadowColor: self.shadowColor, circleColor: self.fillColor) } func drawNavigation_puck(fillColor: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000), puckColor: UIColor = UIColor(red: 0.149, green: 0.239, blue: 0.341, alpha: 1.000), shadowColor: UIColor = UIColor(red: 0.149, green: 0.239, blue: 0.341, alpha: 0.160), circleColor: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)) { diff --git a/MapboxNavigation/VisualInstruction.swift b/MapboxNavigation/VisualInstruction.swift index 151abeca..831b8b68 100644 --- a/MapboxNavigation/VisualInstruction.swift +++ b/MapboxNavigation/VisualInstruction.swift @@ -20,7 +20,7 @@ extension VisualInstruction { mv.scale = UIScreen.main.scale mv.visualInstruction = self let image = mv.imageRepresentation - return shouldFlipImage(side: side) ? image?.withHorizontallyFlippedOrientation() : image + return self.shouldFlipImage(side: side) ? image?.withHorizontallyFlippedOrientation() : image } guard blackAndWhiteManeuverIcons.count == 2 else { return nil } return CPImageSet(lightContentImage: blackAndWhiteManeuverIcons[1], darkContentImage: blackAndWhiteManeuverIcons[0]) diff --git a/MapboxNavigation/VisualInstructionComponent.swift b/MapboxNavigation/VisualInstructionComponent.swift index 6be8ea57..be7e625c 100644 --- a/MapboxNavigation/VisualInstructionComponent.swift +++ b/MapboxNavigation/VisualInstructionComponent.swift @@ -10,7 +10,7 @@ extension VisualInstructionComponent { guard let exitCode = text else { return nil } return "exit-" + exitCode + "-\(VisualInstructionComponent.scale)" case .image: - guard let imageURL else { return genericCacheKey } + guard let imageURL else { return self.genericCacheKey } return "\(imageURL.absoluteString)-\(VisualInstructionComponent.scale)" case .text, .delimiter: return nil diff --git a/MapboxNavigation/Waypoint.swift b/MapboxNavigation/Waypoint.swift index 1fb4243b..ef7e087f 100644 --- a/MapboxNavigation/Waypoint.swift +++ b/MapboxNavigation/Waypoint.swift @@ -12,6 +12,6 @@ extension Waypoint { } var instructionComponents: [VisualInstructionComponent]? { - (instructionComponent != nil) ? [instructionComponent!] : nil + (self.instructionComponent != nil) ? [self.instructionComponent!] : nil } } diff --git a/MapboxNavigationTests/Sources/Support/ImageDownloadOperationSpy.swift b/MapboxNavigationTests/Sources/Support/ImageDownloadOperationSpy.swift index c266a914..3af5a8b0 100644 --- a/MapboxNavigationTests/Sources/Support/ImageDownloadOperationSpy.swift +++ b/MapboxNavigationTests/Sources/Support/ImageDownloadOperationSpy.swift @@ -23,14 +23,14 @@ class ImageDownloadOperationSpy: Operation, ImageDownload { } static func reset() { - operations.removeAll() + self.operations.removeAll() } /** * Retrieve an operation spy instance for the given URL, which can then be used to inspect and/or execute completion handlers */ static func operationForURL(_ URL: URL) -> ImageDownloadOperationSpy? { - operations[URL] + self.operations[URL] } func addCompletion(_ completion: @escaping ImageDownloadCompletionBlock) { @@ -39,7 +39,7 @@ class ImageDownloadOperationSpy: Operation, ImageDownload { // Sadly we need to tick the run loop here to deal with the fact that the underlying implementations hop between queues. This has a similar effect to using XCTestCase's async expectations. RunLoop.current.run(until: Date()) } - completionBlocks.append(wrappedCompletion) + self.completionBlocks.append(wrappedCompletion) } func shouldDecompressImages() -> Bool { @@ -55,7 +55,7 @@ class ImageDownloadOperationSpy: Operation, ImageDownload { func setCredential(_ value: URLCredential?) {} func fireAllCompletions(_ image: UIImage, data: Data?, error: Error?) { - for completion in completionBlocks { + for completion in self.completionBlocks { completion(image, data, error) } } diff --git a/MapboxNavigationTests/Sources/Support/ImageLoadingURLProtocolSpy.swift b/MapboxNavigationTests/Sources/Support/ImageLoadingURLProtocolSpy.swift index 127d1327..607e0d96 100644 --- a/MapboxNavigationTests/Sources/Support/ImageLoadingURLProtocolSpy.swift +++ b/MapboxNavigationTests/Sources/Support/ImageLoadingURLProtocolSpy.swift @@ -13,11 +13,11 @@ class ImageLoadingURLProtocolSpy: URLProtocol { private var loadingStopped: Bool = false override class func canInit(with request: URLRequest) -> Bool { - responseData.keys.contains(request.url!) + self.responseData.keys.contains(request.url!) } override class func canInit(with task: URLSessionTask) -> Bool { - let keys = responseData.keys + let keys = self.responseData.keys return keys.contains(task.currentRequest!.url!) || keys.contains(task.originalRequest!.url!) } @@ -71,37 +71,37 @@ class ImageLoadingURLProtocolSpy: URLProtocol { } override func stopLoading() { - loadingStopped = true + self.loadingStopped = true } /** * Registers data for a given URL */ class func registerData(_ data: Data, forURL url: URL) { - responseData[url] = data + self.responseData[url] = data } /** * Reset stubbed data, active and past requests */ class func reset() { - responseData = [:] - activeRequests = [:] - pastRequests = [:] + self.responseData = [:] + self.activeRequests = [:] + self.pastRequests = [:] } /** * Indicates whether a request for the given URL is in progress */ class func hasActiveRequestForURL(_ url: URL) -> Bool { - activeRequests.keys.contains(url) + self.activeRequests.keys.contains(url) } /** * Returns the most recently completed request for the given URL */ class func pastRequestForURL(_ url: URL) -> URLRequest? { - pastRequests[url] + self.pastRequests[url] } /** diff --git a/MapboxNavigationTests/Sources/Tests/DataCacheTests.swift b/MapboxNavigationTests/Sources/Tests/DataCacheTests.swift index 275aa9f3..802b4b99 100644 --- a/MapboxNavigationTests/Sources/Tests/DataCacheTests.swift +++ b/MapboxNavigationTests/Sources/Tests/DataCacheTests.swift @@ -6,7 +6,7 @@ class DataCacheTests: XCTestCase { private func clearDisk() { let semaphore = DispatchSemaphore(value: 0) - cache.clearDisk { + self.cache.clearDisk { semaphore.signal() } let semaphoreResult = semaphore.wait(timeout: XCTestCase.NavigationTests.timeout) @@ -17,8 +17,8 @@ class DataCacheTests: XCTestCase { super.setUp() continueAfterFailure = false - cache.clearMemory() - clearDisk() + self.cache.clearMemory() + self.clearDisk() } let dataKey = "dataKey" @@ -35,7 +35,7 @@ class DataCacheTests: XCTestCase { private func storeDataInMemory() { let semaphore = DispatchSemaphore(value: 0) - cache.store(exampleData!, forKey: dataKey, toDisk: false) { + self.cache.store(self.exampleData!, forKey: self.dataKey, toDisk: false) { semaphore.signal() } let semaphoreResult = semaphore.wait(timeout: XCTestCase.NavigationTests.timeout) @@ -44,7 +44,7 @@ class DataCacheTests: XCTestCase { private func storeDataOnDisk() { let semaphore = DispatchSemaphore(value: 0) - cache.store(exampleData!, forKey: dataKey, toDisk: true) { + self.cache.store(self.exampleData!, forKey: self.dataKey, toDisk: true) { semaphore.signal() } let semaphoreResult = semaphore.wait(timeout: XCTestCase.NavigationTests.timeout) @@ -54,45 +54,45 @@ class DataCacheTests: XCTestCase { // MARK: Tests func testStoringDataInMemoryOnly() { - storeDataInMemory() + self.storeDataInMemory() - let returnedData = cache.data(forKey: dataKey) + let returnedData = self.cache.data(forKey: self.dataKey) XCTAssertNotNil(returnedData) } func testStoringDataOnDisk() { - storeDataOnDisk() + self.storeDataOnDisk() - var returnedData = cache.data(forKey: dataKey) + var returnedData = self.cache.data(forKey: self.dataKey) XCTAssertNotNil(returnedData) - cache.clearMemory() + self.cache.clearMemory() - returnedData = cache.data(forKey: dataKey) + returnedData = self.cache.data(forKey: self.dataKey) XCTAssertNotNil(returnedData) } func testResettingCache() { - storeDataInMemory() + self.storeDataInMemory() - cache.clearMemory() + self.cache.clearMemory() - XCTAssertNil(cache.data(forKey: dataKey)) + XCTAssertNil(self.cache.data(forKey: self.dataKey)) - storeDataOnDisk() + self.storeDataOnDisk() - cache.clearMemory() - clearDisk() + self.cache.clearMemory() + self.clearDisk() - XCTAssertNil(cache.data(forKey: dataKey)) + XCTAssertNil(self.cache.data(forKey: self.dataKey)) } func testClearingMemoryCacheOnMemoryWarning() { - storeDataInMemory() + self.storeDataInMemory() NotificationCenter.default.post(name: UIApplication.didReceiveMemoryWarningNotification, object: nil) - XCTAssertNil(cache.data(forKey: dataKey)) + XCTAssertNil(self.cache.data(forKey: self.dataKey)) } func testNotificationObserverDoesNotCrash() { @@ -106,13 +106,13 @@ class DataCacheTests: XCTestCase { func testCacheKeyForKey() { let threeMileInstruction = "Continue on I-80 East for 3 miles" let sixMileInstruction = "Continue on I-80 East for 6 miles" - XCTAssertNotEqual(cache.fileCache.cacheKeyForKey(threeMileInstruction), cache.fileCache.cacheKeyForKey(sixMileInstruction)) - XCTAssertNotEqual(cache.fileCache.cacheKeyForKey(""), cache.fileCache.cacheKeyForKey(" ")) - XCTAssertNotEqual(cache.fileCache.cacheKeyForKey("i"), cache.fileCache.cacheKeyForKey("I")) - XCTAssertNotEqual(cache.fileCache.cacheKeyForKey("{"), cache.fileCache.cacheKeyForKey("}")) - XCTAssertEqual(cache.fileCache.cacheKeyForKey("hello"), cache.fileCache.cacheKeyForKey("hello")) - XCTAssertEqual(cache.fileCache.cacheKeyForKey("https://cool.com/neat"), cache.fileCache.cacheKeyForKey("https://cool.com/neat")) - XCTAssertEqual(cache.fileCache.cacheKeyForKey("-"), cache.fileCache.cacheKeyForKey("-")) + XCTAssertNotEqual(self.cache.fileCache.cacheKeyForKey(threeMileInstruction), self.cache.fileCache.cacheKeyForKey(sixMileInstruction)) + XCTAssertNotEqual(self.cache.fileCache.cacheKeyForKey(""), self.cache.fileCache.cacheKeyForKey(" ")) + XCTAssertNotEqual(self.cache.fileCache.cacheKeyForKey("i"), self.cache.fileCache.cacheKeyForKey("I")) + XCTAssertNotEqual(self.cache.fileCache.cacheKeyForKey("{"), self.cache.fileCache.cacheKeyForKey("}")) + XCTAssertEqual(self.cache.fileCache.cacheKeyForKey("hello"), self.cache.fileCache.cacheKeyForKey("hello")) + XCTAssertEqual(self.cache.fileCache.cacheKeyForKey("https://cool.com/neat"), self.cache.fileCache.cacheKeyForKey("https://cool.com/neat")) + XCTAssertEqual(self.cache.fileCache.cacheKeyForKey("-"), self.cache.fileCache.cacheKeyForKey("-")) } /// NOTE: This test is disabled pending https://github.com/mapbox/mapbox-navigation-ios/issues/1468 @@ -121,8 +121,8 @@ class DataCacheTests: XCTestCase { let instructionContinue = "Continue on I-80 East for 3 miles" measure { for _ in 0 ... 1000 { - _ = cache.fileCache.cacheKeyForKey(instructionTurn) - _ = cache.fileCache.cacheKeyForKey(instructionContinue) + _ = self.cache.fileCache.cacheKeyForKey(instructionTurn) + _ = self.cache.fileCache.cacheKeyForKey(instructionContinue) } } } diff --git a/MapboxNavigationTests/Sources/Tests/ImageCacheTests.swift b/MapboxNavigationTests/Sources/Tests/ImageCacheTests.swift index 2fb47ea9..9c7f7f8d 100644 --- a/MapboxNavigationTests/Sources/Tests/ImageCacheTests.swift +++ b/MapboxNavigationTests/Sources/Tests/ImageCacheTests.swift @@ -7,7 +7,7 @@ class ImageCacheTests: XCTestCase { private func clearDiskCache() { let semaphore = DispatchSemaphore(value: 0) - cache.clearDisk { + self.cache.clearDisk { semaphore.signal() } let semaphoreResult = semaphore.wait(timeout: XCTestCase.NavigationTests.timeout) @@ -18,15 +18,15 @@ class ImageCacheTests: XCTestCase { super.setUp() continueAfterFailure = false - cache.clearMemory() - clearDiskCache() + self.cache.clearMemory() + self.clearDiskCache() } let imageKey = "imageKey" private func storeImageInMemory() { let semaphore = DispatchSemaphore(value: 0) - cache.store(ShieldImage.i280.image, forKey: imageKey, toDisk: false) { + self.cache.store(ShieldImage.i280.image, forKey: self.imageKey, toDisk: false) { semaphore.signal() } let semaphoreResult = semaphore.wait(timeout: XCTestCase.NavigationTests.timeout) @@ -35,7 +35,7 @@ class ImageCacheTests: XCTestCase { private func storeImageOnDisk() { let semaphore = DispatchSemaphore(value: 0) - cache.store(ShieldImage.i280.image, forKey: imageKey, toDisk: true) { + self.cache.store(ShieldImage.i280.image, forKey: self.imageKey, toDisk: true) { semaphore.signal() } let semaphoreResult = semaphore.wait(timeout: XCTestCase.NavigationTests.timeout) @@ -47,68 +47,68 @@ class ImageCacheTests: XCTestCase { func testUsingURLStringAsCacheKey() { let cacheKeyURLString = "https://zombo.com/lulz/shieldKey.xyz" let expectation = expectation(description: "Storing image in disk cache") - cache.store(ShieldImage.i280.image, forKey: cacheKeyURLString, toDisk: true) { + self.cache.store(ShieldImage.i280.image, forKey: cacheKeyURLString, toDisk: true) { expectation.fulfill() } - wait(for: [expectation], timeout: asyncTimeout) + wait(for: [expectation], timeout: self.asyncTimeout) - let returnedImage = cache.image(forKey: cacheKeyURLString) + let returnedImage = self.cache.image(forKey: cacheKeyURLString) XCTAssertTrue((returnedImage?.isKind(of: UIImage.self))!) } func testUsingPathStringAsCacheKey() { let cacheKeyURLString = "/path/to/something.xyz" let expectation = expectation(description: "Storing image in disk cache") - cache.store(ShieldImage.i280.image, forKey: cacheKeyURLString, toDisk: true) { + self.cache.store(ShieldImage.i280.image, forKey: cacheKeyURLString, toDisk: true) { expectation.fulfill() } - wait(for: [expectation], timeout: asyncTimeout) + wait(for: [expectation], timeout: self.asyncTimeout) - let returnedImage = cache.image(forKey: cacheKeyURLString) + let returnedImage = self.cache.image(forKey: cacheKeyURLString) XCTAssertTrue((returnedImage?.isKind(of: UIImage.self))!) } func testStoringImageInMemoryOnly() { - storeImageInMemory() + self.storeImageInMemory() - let returnedImage = cache.image(forKey: imageKey) + let returnedImage = self.cache.image(forKey: self.imageKey) XCTAssertTrue((returnedImage?.isKind(of: UIImage.self))!) } func testStoringImageOnDisk() { - storeImageOnDisk() + self.storeImageOnDisk() - var returnedImage = cache.image(forKey: imageKey) + var returnedImage = self.cache.image(forKey: self.imageKey) XCTAssertTrue((returnedImage?.isKind(of: UIImage.self))!) - cache.clearMemory() + self.cache.clearMemory() - returnedImage = cache.image(forKey: imageKey) + returnedImage = self.cache.image(forKey: self.imageKey) XCTAssertNotNil(returnedImage) XCTAssertTrue((returnedImage?.isKind(of: UIImage.self))!) } func testResettingCache() { - storeImageInMemory() + self.storeImageInMemory() - cache.clearMemory() + self.cache.clearMemory() - XCTAssertNil(cache.image(forKey: imageKey)) + XCTAssertNil(self.cache.image(forKey: self.imageKey)) - storeImageOnDisk() + self.storeImageOnDisk() - cache.clearMemory() - clearDiskCache() + self.cache.clearMemory() + self.clearDiskCache() - XCTAssertNil(cache.image(forKey: imageKey)) + XCTAssertNil(self.cache.image(forKey: self.imageKey)) } func testClearingMemoryCacheOnMemoryWarning() { - storeImageInMemory() + self.storeImageInMemory() NotificationCenter.default.post(name: UIApplication.didReceiveMemoryWarningNotification, object: nil) - XCTAssertNil(cache.image(forKey: imageKey)) + XCTAssertNil(self.cache.image(forKey: self.imageKey)) } func testJPEGSupport() { @@ -116,12 +116,12 @@ class ImageCacheTests: XCTestCase { let image = UIImage(data: imageJPEGData)! let expectation = expectation(description: "Storing image in disk cache") - cache.store(image, forKey: "JPEG Test", toDisk: true) { + self.cache.store(image, forKey: "JPEG Test", toDisk: true) { expectation.fulfill() } - wait(for: [expectation], timeout: asyncTimeout) + wait(for: [expectation], timeout: self.asyncTimeout) - let retrievedImage = cache.image(forKey: "JPEG Test")! + let retrievedImage = self.cache.image(forKey: "JPEG Test")! XCTAssertTrue(retrievedImage.isKind(of: UIImage.self)) } diff --git a/MapboxNavigationTests/Sources/Tests/ImageDownloaderTests.swift b/MapboxNavigationTests/Sources/Tests/ImageDownloaderTests.swift index 04169a55..319094e7 100644 --- a/MapboxNavigationTests/Sources/Tests/ImageDownloaderTests.swift +++ b/MapboxNavigationTests/Sources/Tests/ImageDownloaderTests.swift @@ -19,13 +19,13 @@ class ImageDownloaderTests: XCTestCase { ImageLoadingURLProtocolSpy.reset() let imageData = ShieldImage.i280.image.pngData()! - ImageLoadingURLProtocolSpy.registerData(imageData, forURL: imageURL) + ImageLoadingURLProtocolSpy.registerData(imageData, forURL: self.imageURL) - downloader = ImageDownloader(sessionConfiguration: sessionConfig) + self.downloader = ImageDownloader(sessionConfiguration: self.sessionConfig) } override func tearDown() { - downloader = nil + self.downloader = nil super.tearDown() } @@ -40,7 +40,7 @@ class ImageDownloaderTests: XCTestCase { var errorReturned: Error? let semaphore = DispatchSemaphore(value: 0) - downloader.downloadImage(with: imageURL) { image, data, error in + downloader.downloadImage(with: self.imageURL) { image, data, error in imageReturned = image dataReturned = data errorReturned = error @@ -50,7 +50,7 @@ class ImageDownloaderTests: XCTestCase { XCTAssert(semaphoreResult == .success, "Semaphore timed out") // The ImageDownloader is meant to be used with an external caching mechanism - let request = ImageLoadingURLProtocolSpy.pastRequestForURL(imageURL)! + let request = ImageLoadingURLProtocolSpy.pastRequestForURL(self.imageURL)! XCTAssertEqual(request.cachePolicy, .reloadIgnoringCacheData) XCTAssertNotNil(imageReturned) @@ -71,19 +71,19 @@ class ImageDownloaderTests: XCTestCase { // URL loading is delayed in order to simulate conditions under which multiple requests for the same asset would be made ImageLoadingURLProtocolSpy.delayImageLoading() - downloader.downloadImage(with: imageURL) { _, _, _ in + downloader.downloadImage(with: self.imageURL) { _, _, _ in firstCallbackCalled = true } - operation = downloader.activeOperation(with: imageURL)! + operation = downloader.activeOperation(with: self.imageURL)! - downloader.downloadImage(with: imageURL) { _, _, _ in + downloader.downloadImage(with: self.imageURL) { _, _, _ in secondCallbackCalled = true } ImageLoadingURLProtocolSpy.resumeImageLoading() - XCTAssertTrue(operation === downloader.activeOperation(with: imageURL)!, - "Expected \(String(describing: operation)) to be identical to \(String(describing: downloader.activeOperation(with: imageURL)))") + XCTAssertTrue(operation === downloader.activeOperation(with: self.imageURL)!, + "Expected \(String(describing: operation)) to be identical to \(String(describing: downloader.activeOperation(with: self.imageURL)))") var spinCount = 0 @@ -106,10 +106,10 @@ class ImageDownloaderTests: XCTestCase { var callbackCalled = false var spinCount = 0 - downloader.downloadImage(with: imageURL) { _, _, _ in + downloader.downloadImage(with: self.imageURL) { _, _, _ in callbackCalled = true } - var operation = downloader.activeOperation(with: imageURL)! + var operation = downloader.activeOperation(with: self.imageURL)! runUntil { spinCount += 1 @@ -122,10 +122,10 @@ class ImageDownloaderTests: XCTestCase { callbackCalled = false spinCount = 0 - downloader.downloadImage(with: imageURL) { _, _, _ in + downloader.downloadImage(with: self.imageURL) { _, _, _ in callbackCalled = true } - operation = downloader.activeOperation(with: imageURL)! + operation = downloader.activeOperation(with: self.imageURL)! runUntil { spinCount += 1 diff --git a/MapboxNavigationTests/Sources/Tests/ImageRepositoryTests.swift b/MapboxNavigationTests/Sources/Tests/ImageRepositoryTests.swift index dbc88f4a..75e4f1cd 100644 --- a/MapboxNavigationTests/Sources/Tests/ImageRepositoryTests.swift +++ b/MapboxNavigationTests/Sources/Tests/ImageRepositoryTests.swift @@ -18,7 +18,7 @@ class ImageRepositoryTests: XCTestCase { ImageLoadingURLProtocolSpy.reset() let semaphore = DispatchSemaphore(value: 0) - repository.resetImageCache { + self.repository.resetImageCache { semaphore.signal() } let semaphoreResult = semaphore.wait(timeout: XCTestCase.NavigationTests.timeout) @@ -34,12 +34,12 @@ class ImageRepositoryTests: XCTestCase { let fakeURL = URL(string: "http://an.image.url/\(imageName)")! ImageLoadingURLProtocolSpy.registerData(ShieldImage.i280.image.pngData()!, forURL: fakeURL) - XCTAssertNil(repository.cachedImageForKey(imageName)) + XCTAssertNil(self.repository.cachedImageForKey(imageName)) var imageReturned: UIImage? = nil let semaphore = DispatchSemaphore(value: 0) - repository.imageWithURL(fakeURL, cacheKey: imageName) { image in + self.repository.imageWithURL(fakeURL, cacheKey: imageName) { image in imageReturned = image semaphore.signal() } @@ -55,12 +55,12 @@ class ImageRepositoryTests: XCTestCase { let imageName = "1.png" let fakeURL = URL(string: "http://an.image.url/\(imageName)")! - repository.storeImage(ShieldImage.i280.image, forKey: imageName, toDisk: false) + self.repository.storeImage(ShieldImage.i280.image, forKey: imageName, toDisk: false) var imageReturned: UIImage? = nil let semaphore = DispatchSemaphore(value: 0) - repository.imageWithURL(fakeURL, cacheKey: imageName) { image in + self.repository.imageWithURL(fakeURL, cacheKey: imageName) { image in imageReturned = image semaphore.signal() } diff --git a/MapboxNavigationTests/Sources/Tests/InstructionsBannerViewIntegrationTests.swift b/MapboxNavigationTests/Sources/Tests/InstructionsBannerViewIntegrationTests.swift index a56c1edd..c631b716 100644 --- a/MapboxNavigationTests/Sources/Tests/InstructionsBannerViewIntegrationTests.swift +++ b/MapboxNavigationTests/Sources/Tests/InstructionsBannerViewIntegrationTests.swift @@ -49,7 +49,7 @@ class InstructionsBannerViewIntegrationTests: XCTestCase { private func resetImageCache() { let semaphore = DispatchSemaphore(value: 0) - imageRepository.resetImageCache { + self.imageRepository.resetImageCache { semaphore.signal() } let semaphoreResult = semaphore.wait(timeout: XCTestCase.NavigationTests.timeout) @@ -60,33 +60,33 @@ class InstructionsBannerViewIntegrationTests: XCTestCase { super.setUp() continueAfterFailure = false - imageRepository.disableDiskCache() - resetImageCache() + self.imageRepository.disableDiskCache() + self.resetImageCache() ImageDownloadOperationSpy.reset() - imageRepository.imageDownloader.setOperationType(ImageDownloadOperationSpy.self) + self.imageRepository.imageDownloader.setOperationType(ImageDownloadOperationSpy.self) } override func tearDown() { - imageRepository.imageDownloader.setOperationType(nil) + self.imageRepository.imageDownloader.setOperationType(nil) super.tearDown() } func testCustomVisualInstructionDelegate() { let view = instructionsView() - view.instructionDelegate = reverseDelegate + view.instructionDelegate = self.reverseDelegate - view.update(for: typicalInstruction) + view.update(for: self.typicalInstruction) XCTAssert(view.primaryLabel.attributedText?.string == "teertS niaM") } func testCustomDelegateReturningNilTriggersDefaultBehavior() { let view = instructionsView() - view.instructionDelegate = silentDelegate + view.instructionDelegate = self.silentDelegate - view.update(for: typicalInstruction) + view.update(for: self.typicalInstruction) XCTAssert(view.primaryLabel.attributedText?.string == "Main Street") } @@ -94,7 +94,7 @@ class InstructionsBannerViewIntegrationTests: XCTestCase { func testDelimiterIsShownWhenShieldsNotLoaded() { let view = instructionsView() - view.update(for: makeVisualInstruction(primaryInstruction: instructions, secondaryInstruction: nil)) + view.update(for: makeVisualInstruction(primaryInstruction: self.instructions, secondaryInstruction: nil)) XCTAssertNotNil(view.primaryLabel.text!.firstIndex(of: "/")) } @@ -104,17 +104,17 @@ class InstructionsBannerViewIntegrationTests: XCTestCase { let instruction1 = VisualInstructionComponent(type: .image, text: "I 280", imageURL: ShieldImage.i280.url, abbreviation: nil, abbreviationPriority: 0) let instruction2 = VisualInstructionComponent(type: .image, text: "US 101", imageURL: ShieldImage.us101.url, abbreviation: nil, abbreviationPriority: 0) - imageRepository.storeImage(ShieldImage.i280.image, forKey: instruction1.cacheKey!, toDisk: false) - imageRepository.storeImage(ShieldImage.us101.image, forKey: instruction2.cacheKey!, toDisk: false) + self.imageRepository.storeImage(ShieldImage.i280.image, forKey: instruction1.cacheKey!, toDisk: false) + self.imageRepository.storeImage(ShieldImage.us101.image, forKey: instruction2.cacheKey!, toDisk: false) let view = instructionsView() - view.update(for: makeVisualInstruction(primaryInstruction: instructions, secondaryInstruction: nil)) + view.update(for: makeVisualInstruction(primaryInstruction: self.instructions, secondaryInstruction: nil)) // the delimiter should NOT be present since both shields are already in the cache XCTAssertNil(view.primaryLabel.text!.firstIndex(of: "/")) // explicitly reset the cache - resetImageCache() + self.resetImageCache() } func testDelimiterDisappearsOnlyWhenAllShieldsHaveLoaded() { @@ -130,14 +130,14 @@ class InstructionsBannerViewIntegrationTests: XCTestCase { } // set visual instructions on the view, which triggers the instruction image fetch - view.update(for: makeVisualInstruction(primaryInstruction: instructions, secondaryInstruction: nil)) + view.update(for: makeVisualInstruction(primaryInstruction: self.instructions, secondaryInstruction: nil)) // Slash should be present until an adjacent shield is downloaded XCTAssertNotNil(view.primaryLabel.text!.firstIndex(of: "/")) // simulate the downloads - let firstDestinationComponent: VisualInstructionComponent = instructions[0] - simulateDownloadingShieldForComponent(firstDestinationComponent) + let firstDestinationComponent: VisualInstructionComponent = self.instructions[0] + self.simulateDownloadingShieldForComponent(firstDestinationComponent) // ensure that first callback fires wait(for: [firstExpectation], timeout: 1) @@ -145,8 +145,8 @@ class InstructionsBannerViewIntegrationTests: XCTestCase { // change the callback to track the second shield component view.primaryLabel.imageDownloadCompletion = secondExpectation.fulfill - let secondDestinationComponent = instructions[2] - simulateDownloadingShieldForComponent(secondDestinationComponent) + let secondDestinationComponent = self.instructions[2] + self.simulateDownloadingShieldForComponent(secondDestinationComponent) // ensure that second callback fires wait(for: [secondExpectation], timeout: 1) @@ -195,7 +195,7 @@ class InstructionsBannerViewIntegrationTests: XCTestCase { } // set visual instructions on the view, which triggers the instruction image fetch - view.update(for: makeVisualInstruction(primaryInstruction: instructions, secondaryInstruction: nil)) + view.update(for: makeVisualInstruction(primaryInstruction: self.instructions, secondaryInstruction: nil)) let firstAttachmentRange = NSRange(location: 0, length: 1) let secondAttachmentRange = NSRange(location: 4, length: 1) @@ -220,8 +220,8 @@ class InstructionsBannerViewIntegrationTests: XCTestCase { }) // simulate the downloads - let firstDestinationComponent: VisualInstructionComponent = instructions[0] - simulateDownloadingShieldForComponent(firstDestinationComponent) + let firstDestinationComponent: VisualInstructionComponent = self.instructions[0] + self.simulateDownloadingShieldForComponent(firstDestinationComponent) // ensure that first callback fires wait(for: [firstExpectation], timeout: 1) @@ -246,8 +246,8 @@ class InstructionsBannerViewIntegrationTests: XCTestCase { // change the callback to track the second shield component view.primaryLabel.imageDownloadCompletion = secondExpectation.fulfill - let secondDestinationComponent = instructions[2] - simulateDownloadingShieldForComponent(secondDestinationComponent) + let secondDestinationComponent = self.instructions[2] + self.simulateDownloadingShieldForComponent(secondDestinationComponent) // ensure that second callback fires wait(for: [secondExpectation], timeout: 1) @@ -290,7 +290,7 @@ class InstructionsBannerViewIntegrationTests: XCTestCase { let attributed = presenter.attributedText() let key = [exitCodeAttribute.cacheKey!, ExitView.criticalHash(side: .right, dataSource: label)].joined(separator: "-") - XCTAssertNotNil(imageRepository.cachedImageForKey(key), "Expected cached image") + XCTAssertNotNil(self.imageRepository.cachedImageForKey(key), "Expected cached image") let spaceRange = NSMakeRange(1, 1) let space = attributed.attributedSubstring(from: spaceRange) @@ -309,7 +309,7 @@ class InstructionsBannerViewIntegrationTests: XCTestCase { let operation = ImageDownloadOperationSpy.operationForURL(component.imageURL!)! operation.fireAllCompletions(ShieldImage.i280.image, data: ShieldImage.i280.image.pngData(), error: nil) - XCTAssertNotNil(imageRepository.cachedImageForKey(component.cacheKey!)) + XCTAssertNotNil(self.imageRepository.cachedImageForKey(component.cacheKey!)) } } diff --git a/MapboxNavigationTests/Sources/Tests/NavigationMapViewTests.swift b/MapboxNavigationTests/Sources/Tests/NavigationMapViewTests.swift index 403afbd2..aee3d6b7 100644 --- a/MapboxNavigationTests/Sources/Tests/NavigationMapViewTests.swift +++ b/MapboxNavigationTests/Sources/Tests/NavigationMapViewTests.swift @@ -16,7 +16,7 @@ class NavigationMapViewTests: XCTestCase { func testNavigationMapViewCombineWithSimilarCongestions() { let navigationMapView = NavigationMapView(frame: CGRect(origin: .zero, size: .iPhone6Plus)) - let congestionSegments = navigationMapView.combine(coordinates, with: [ + let congestionSegments = navigationMapView.combine(self.coordinates, with: [ .low, .low, .low, @@ -32,7 +32,7 @@ class NavigationMapViewTests: XCTestCase { func testNavigationMapViewCombineWithDissimilarCongestions() { let navigationMapView = NavigationMapView(frame: CGRect(origin: .zero, size: .iPhone6Plus)) - let congestionSegmentsSevere = navigationMapView.combine(coordinates, with: [ + let congestionSegmentsSevere = navigationMapView.combine(self.coordinates, with: [ .low, .low, .severe, diff --git a/MapboxNavigationTests/Sources/Tests/NavigationViewControllerTests.swift b/MapboxNavigationTests/Sources/Tests/NavigationViewControllerTests.swift index cd183ecb..5253487c 100644 --- a/MapboxNavigationTests/Sources/Tests/NavigationViewControllerTests.swift +++ b/MapboxNavigationTests/Sources/Tests/NavigationViewControllerTests.swift @@ -65,19 +65,19 @@ class NavigationViewControllerTests: XCTestCase { override func setUp() { super.setUp() - customRoadName.removeAll() + self.customRoadName.removeAll() } // Brief: navigationViewController(_:roadNameAt:) delegate method is implemented, // with a road name provided and wayNameView label is visible. func testNavigationViewControllerDelegateRoadNameAtLocationImplemented() { - let navigationViewController = dependencies.navigationViewController + let navigationViewController = self.dependencies.navigationViewController let routeController = navigationViewController.routeController! // Identify a location to set the custom road name. - let taylorStreetLocation = dependencies.poi.first! + let taylorStreetLocation = self.dependencies.poi.first! let roadName = "Taylor Swift Street" - customRoadName[taylorStreetLocation.coordinate] = roadName + self.customRoadName[taylorStreetLocation.coordinate] = roadName routeController.locationManager(routeController.locationManager, didUpdateLocations: [taylorStreetLocation]) @@ -92,14 +92,14 @@ class NavigationViewControllerTests: XCTestCase { let routeController = navigationViewController.routeController! navigationViewController.styleManager.delegate = self - let someLocation = dependencies.poi.first! + let someLocation = self.dependencies.poi.first! routeController.locationManager(routeController.locationManager, didUpdateLocations: [someLocation]) routeController.locationManager(routeController.locationManager, didUpdateLocations: [someLocation]) routeController.locationManager(routeController.locationManager, didUpdateLocations: [someLocation]) - XCTAssertEqual(updatedStyleNumberOfTimes, 0, "The style should not be updated.") - updatedStyleNumberOfTimes = 0 + XCTAssertEqual(self.updatedStyleNumberOfTimes, 0, "The style should not be updated.") + self.updatedStyleNumberOfTimes = 0 } // If tunnel flags are enabled and we need to switch styles, we should not force refresh the map style because we have only 1 style. @@ -108,14 +108,14 @@ class NavigationViewControllerTests: XCTestCase { let routeController = navigationViewController.routeController! navigationViewController.styleManager.delegate = self - let someLocation = dependencies.poi.first! + let someLocation = self.dependencies.poi.first! routeController.locationManager(routeController.locationManager, didUpdateLocations: [someLocation]) routeController.locationManager(routeController.locationManager, didUpdateLocations: [someLocation]) routeController.locationManager(routeController.locationManager, didUpdateLocations: [someLocation]) - XCTAssertEqual(updatedStyleNumberOfTimes, 0, "The style should not be updated.") - updatedStyleNumberOfTimes = 0 + XCTAssertEqual(self.updatedStyleNumberOfTimes, 0, "The style should not be updated.") + self.updatedStyleNumberOfTimes = 0 } func testNavigationShouldNotCallStyleManagerDidRefreshAppearanceMoreThanOnceWithTwoStyles() { @@ -123,26 +123,26 @@ class NavigationViewControllerTests: XCTestCase { let routeController = navigationViewController.routeController! navigationViewController.styleManager.delegate = self - let someLocation = dependencies.poi.first! + let someLocation = self.dependencies.poi.first! routeController.locationManager(routeController.locationManager, didUpdateLocations: [someLocation]) routeController.locationManager(routeController.locationManager, didUpdateLocations: [someLocation]) routeController.locationManager(routeController.locationManager, didUpdateLocations: [someLocation]) - XCTAssertEqual(updatedStyleNumberOfTimes, 0, "The style should not be updated.") - updatedStyleNumberOfTimes = 0 + XCTAssertEqual(self.updatedStyleNumberOfTimes, 0, "The style should not be updated.") + self.updatedStyleNumberOfTimes = 0 } // Brief: navigationViewController(_:roadNameAt:) delegate method is implemented, // with a blank road name (empty string) provided and wayNameView label is hidden. func testNavigationViewControllerDelegateRoadNameAtLocationEmptyString() { - let navigationViewController = dependencies.navigationViewController + let navigationViewController = self.dependencies.navigationViewController let routeController = navigationViewController.routeController! // Identify a location to set the custom road name. - let turkStreetLocation = dependencies.poi[1] + let turkStreetLocation = self.dependencies.poi[1] let roadName = "" - customRoadName[turkStreetLocation.coordinate] = roadName + self.customRoadName[turkStreetLocation.coordinate] = roadName routeController.locationManager(routeController.locationManager, didUpdateLocations: [turkStreetLocation]) @@ -153,7 +153,7 @@ class NavigationViewControllerTests: XCTestCase { } func testNavigationViewControllerDelegateRoadNameAtLocationUmimplemented() { - let navigationViewController = dependencies.navigationViewController + let navigationViewController = self.dependencies.navigationViewController // We break the communication between CLLocation and MBRouteController // Intent: Prevent the routecontroller from being fed real location updates @@ -162,7 +162,7 @@ class NavigationViewControllerTests: XCTestCase { let routeController = navigationViewController.routeController! // Identify a location without a custom road name. - let fultonStreetLocation = dependencies.poi[2] + let fultonStreetLocation = self.dependencies.poi[2] navigationViewController.mapViewController!.labelRoadNameCompletionHandler = { defaultRaodNameAssigned in XCTAssertTrue(defaultRaodNameAssigned, "label road name was not successfully set") @@ -177,7 +177,7 @@ class NavigationViewControllerTests: XCTestCase { // wait for the style to load -- routes won't show without it. wait(for: [styleLoaded], timeout: 5) - navigationViewController.route = initialRoute + navigationViewController.route = self.initialRoute runUntil { !(navigationViewController.mapView!.annotations?.isEmpty ?? true) @@ -185,18 +185,18 @@ class NavigationViewControllerTests: XCTestCase { guard let annotations = navigationViewController.mapView?.annotations else { return XCTFail("Annotations not found.") } - let firstDestination = initialRoute.routeOptions.waypoints.last!.coordinate - let destinations = annotations.filter(annotationFilter(matching: firstDestination)) + let firstDestination = self.initialRoute.routeOptions.waypoints.last!.coordinate + let destinations = annotations.filter(self.annotationFilter(matching: firstDestination)) XCTAssert(!destinations.isEmpty, "Destination annotation does not exist on map") // lets set the second route - navigationViewController.route = newRoute + navigationViewController.route = self.newRoute guard let newAnnotations = navigationViewController.mapView?.annotations else { return XCTFail("New annotations not found.") } - let secondDestination = newRoute.routeOptions.waypoints.last!.coordinate + let secondDestination = self.newRoute.routeOptions.waypoints.last!.coordinate // do we have a destination on the second route? - let newDestinations = newAnnotations.filter(annotationFilter(matching: secondDestination)) + let newDestinations = newAnnotations.filter(self.annotationFilter(matching: secondDestination)) XCTAssert(!newDestinations.isEmpty, "New destination annotation does not exist on map") } @@ -211,15 +211,15 @@ class NavigationViewControllerTests: XCTestCase { extension NavigationViewControllerTests: NavigationViewControllerDelegate, StyleManagerDelegate { func locationFor(styleManager: StyleManager) -> CLLocation? { - dependencies.poi.first! + self.dependencies.poi.first! } func styleManagerDidRefreshAppearance(_ styleManager: StyleManager) { - updatedStyleNumberOfTimes += 1 + self.updatedStyleNumberOfTimes += 1 } func navigationViewController(_ navigationViewController: NavigationViewController, roadNameAt location: CLLocation) -> String? { - customRoadName[location.coordinate] ?? nil + self.customRoadName[location.coordinate] ?? nil } } @@ -254,7 +254,7 @@ class NavigationViewControllerTestable: NavigationViewController { styles: [Style]? = [DayStyle(), NightStyle()], locationManager: NavigationLocationManager? = NavigationLocationManager(), styleLoaded: XCTestExpectation) { - styleLoadedExpectation = styleLoaded + self.styleLoadedExpectation = styleLoaded super.init(for: route, directions: directions, styles: styles, locationManager: locationManager, voiceController: FakeVoiceController()) } @@ -264,7 +264,7 @@ class NavigationViewControllerTestable: NavigationViewController { } func mapView(_ mapView: MLNMapView, didFinishLoading style: MLNStyle) { - styleLoadedExpectation.fulfill() + self.styleLoadedExpectation.fulfill() } @available(*, unavailable) diff --git a/MapboxNavigationTests/Sources/Tests/StepsViewControllerTests.swift b/MapboxNavigationTests/Sources/Tests/StepsViewControllerTests.swift index 84e38762..83e3e44b 100644 --- a/MapboxNavigationTests/Sources/Tests/StepsViewControllerTests.swift +++ b/MapboxNavigationTests/Sources/Tests/StepsViewControllerTests.swift @@ -36,7 +36,7 @@ class StepsViewControllerTests: XCTestCase { }() func testRebuildStepsInstructionsViewDataSource() { - let stepsViewController = dependencies.stepsViewController + let stepsViewController = self.dependencies.stepsViewController measure { // Measure Performance - stepsViewController.rebuildDataSourceIfNecessary() @@ -50,7 +50,7 @@ class StepsViewControllerTests: XCTestCase { /// NOTE: This test is disabled pending https://github.com/mapbox/mapbox-navigation-ios/issues/1468 func x_testUpdateCellPerformance() { - let stepsViewController = dependencies.stepsViewController + let stepsViewController = self.dependencies.stepsViewController // Test that Steps ViewController viewLoads XCTAssertNotNil(stepsViewController.view, "StepsViewController not initiated properly") diff --git a/MapboxNavigationTests/Sources/Tests/StyleManagerTests.swift b/MapboxNavigationTests/Sources/Tests/StyleManagerTests.swift index 3a116729..f79676d3 100644 --- a/MapboxNavigationTests/Sources/Tests/StyleManagerTests.swift +++ b/MapboxNavigationTests/Sources/Tests/StyleManagerTests.swift @@ -15,12 +15,12 @@ class StyleManagerTests: XCTestCase { override func setUp() { super.setUp() - styleManager = StyleManager(self) - styleManager.automaticallyAdjustsStyleForTimeOfDay = true + self.styleManager = StyleManager(self) + self.styleManager.automaticallyAdjustsStyleForTimeOfDay = true } func testStyleManagerLondon() { - location = Location.london + self.location = Location.london let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm" dateFormatter.timeZone = TimeZone(identifier: "UTC") @@ -32,22 +32,22 @@ class StyleManagerTests: XCTestCase { let afterSunset = dateFormatter.date(from: "21:00")! let midnight = dateFormatter.date(from: "00:00")! - styleManager.date = beforeSunrise - XCTAssert(styleManager.styleType(for: location) == .night) - styleManager.date = afterSunrise - XCTAssert(styleManager.styleType(for: location) == .day) - styleManager.date = noonDate - XCTAssert(styleManager.styleType(for: location) == .day) - styleManager.date = beforeSunset - XCTAssert(styleManager.styleType(for: location) == .day) - styleManager.date = afterSunset - XCTAssert(styleManager.styleType(for: location) == .night) - styleManager.date = midnight - XCTAssert(styleManager.styleType(for: location) == .night) + self.styleManager.date = beforeSunrise + XCTAssert(self.styleManager.styleType(for: self.location) == .night) + self.styleManager.date = afterSunrise + XCTAssert(self.styleManager.styleType(for: self.location) == .day) + self.styleManager.date = noonDate + XCTAssert(self.styleManager.styleType(for: self.location) == .day) + self.styleManager.date = beforeSunset + XCTAssert(self.styleManager.styleType(for: self.location) == .day) + self.styleManager.date = afterSunset + XCTAssert(self.styleManager.styleType(for: self.location) == .night) + self.styleManager.date = midnight + XCTAssert(self.styleManager.styleType(for: self.location) == .night) } func testStyleManagerParisWithSeconds() { - location = Location.paris + self.location = Location.paris let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm:ss" dateFormatter.timeZone = TimeZone(identifier: "CET") @@ -61,22 +61,22 @@ class StyleManagerTests: XCTestCase { let justAfterSunset = dateFormatter.date(from: "17:04:30")! let midnight = dateFormatter.date(from: "00:00:00")! - styleManager.date = justBeforeSunrise - XCTAssert(styleManager.styleType(for: location) == .night) - styleManager.date = justAfterSunrise - XCTAssert(styleManager.styleType(for: location) == .day) - styleManager.date = noonDate - XCTAssert(styleManager.styleType(for: location) == .day) - styleManager.date = juetBeforeSunset - XCTAssert(styleManager.styleType(for: location) == .day) - styleManager.date = justAfterSunset - XCTAssert(styleManager.styleType(for: location) == .night) - styleManager.date = midnight - XCTAssert(styleManager.styleType(for: location) == .night) + self.styleManager.date = justBeforeSunrise + XCTAssert(self.styleManager.styleType(for: self.location) == .night) + self.styleManager.date = justAfterSunrise + XCTAssert(self.styleManager.styleType(for: self.location) == .day) + self.styleManager.date = noonDate + XCTAssert(self.styleManager.styleType(for: self.location) == .day) + self.styleManager.date = juetBeforeSunset + XCTAssert(self.styleManager.styleType(for: self.location) == .day) + self.styleManager.date = justAfterSunset + XCTAssert(self.styleManager.styleType(for: self.location) == .night) + self.styleManager.date = midnight + XCTAssert(self.styleManager.styleType(for: self.location) == .night) } func testStyleManagerSanFrancisco() { - location = Location.sf + self.location = Location.sf let dateFormatter = DateFormatter() dateFormatter.dateFormat = "hh:mm a" dateFormatter.timeZone = TimeZone(identifier: "PST") @@ -90,22 +90,22 @@ class StyleManagerTests: XCTestCase { let afterSunset = dateFormatter.date(from: "09:00 PM")! let midnight = dateFormatter.date(from: "00:00 AM")! - styleManager.date = beforeSunrise - XCTAssert(styleManager.styleType(for: location) == .night) - styleManager.date = afterSunrise - XCTAssert(styleManager.styleType(for: location) == .day) - styleManager.date = noonDate - XCTAssert(styleManager.styleType(for: location) == .day) - styleManager.date = beforeSunset - XCTAssert(styleManager.styleType(for: location) == .day) - styleManager.date = afterSunset - XCTAssert(styleManager.styleType(for: location) == .night) - styleManager.date = midnight - XCTAssert(styleManager.styleType(for: location) == .night) + self.styleManager.date = beforeSunrise + XCTAssert(self.styleManager.styleType(for: self.location) == .night) + self.styleManager.date = afterSunrise + XCTAssert(self.styleManager.styleType(for: self.location) == .day) + self.styleManager.date = noonDate + XCTAssert(self.styleManager.styleType(for: self.location) == .day) + self.styleManager.date = beforeSunset + XCTAssert(self.styleManager.styleType(for: self.location) == .day) + self.styleManager.date = afterSunset + XCTAssert(self.styleManager.styleType(for: self.location) == .night) + self.styleManager.date = midnight + XCTAssert(self.styleManager.styleType(for: self.location) == .night) } func testTimeIntervalsUntilTimeOfDayChanges() { - location = Location.paris + self.location = Location.paris let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm" dateFormatter.timeZone = TimeZone(identifier: "CET") @@ -130,6 +130,6 @@ extension StyleManagerTests: StyleManagerDelegate { func styleManager(_ styleManager: StyleManager, didApply style: Style) {} func locationFor(styleManager: StyleManager) -> CLLocation? { - location + self.location } } diff --git a/MapboxNavigationTests/Sources/Tests/XCTestCase.swift b/MapboxNavigationTests/Sources/Tests/XCTestCase.swift index 596883f8..bb16ff74 100644 --- a/MapboxNavigationTests/Sources/Tests/XCTestCase.swift +++ b/MapboxNavigationTests/Sources/Tests/XCTestCase.swift @@ -11,7 +11,7 @@ extension XCTestCase { } func runUntil(_ condition: () -> Bool, testCase: String = #function) { - runUntil(condition: condition, testCase: testCase, pollingInterval: NavigationTests.pollingInterval, until: NavigationTests.timeout) + self.runUntil(condition: condition, testCase: testCase, pollingInterval: NavigationTests.pollingInterval, until: NavigationTests.timeout) } func runUntil(condition: () -> Bool, testCase: String, pollingInterval: TimeInterval, until timeout: DispatchTime) { @@ -22,7 +22,7 @@ extension XCTestCase { if condition() == false { RunLoop.current.run(until: Date(timeIntervalSinceNow: pollingInterval)) - runUntil(condition: condition, testCase: testCase, pollingInterval: pollingInterval, until: timeout) + self.runUntil(condition: condition, testCase: testCase, pollingInterval: pollingInterval, until: timeout) } } }