Problème d'annotation d'adresse pour une app IOS

Bonjour,
j’ai un bug sur une application IOS de chauffeur taxi, lorsque le taxi reçoit une demande l’adresse de départ et l’adresse est identique, mais quand j’appuie sur le marqueur d’annotation pour avoir le trajet sur google cartes la position est bonne. Et sur l’app client les adresses sont bonnes.Je pense que c’est une inversion de variable.
Merci d’avance

Voici mon code pour l'app chauffeur :



```import UIKit



import MapKit



class DriverTravelViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

  @IBOutlet weak var labelCost: UILabel!

  @IBOutlet weak var labelTime: UILabel!

  @IBOutlet weak var map: MKMapView!

  @IBOutlet weak var buttonStart: UIButton!

  @IBOutlet weak var buttonFinish: UIButton!

  @IBOutlet weak var buttonMessage: UIButton!

  @IBOutlet weak var buttonCall: UIButton!

  @IBOutlet weak var buttonCancel: UIButton!

  @IBOutlet weak var backgroundView: UIView!

  @IBOutlet weak var buttonArrived: ColoredButton!

   

  var timer = Timer()

  var locationManager = CLLocationManager()

  var pointAnnotations: [MKPointAnnotation] = []

  var destinationMarkers: [MKPointAnnotation] = []

  var driverMarker = MKPointAnnotation()

  var route = [CLLocationCoordinate2D]()

  var distance: Double = 0.0

   

  override func viewDidLoad() {

    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(self.travelCanceled), name: .cancelTravel, object: nil)

    NotificationCenter.default.addObserver(self, selector:#selector(self.requestRefresh), name: .connectedAfterForeground, object: nil)

    if let cost = Request.shared.costBest {

      labelCost.text = MyLocale.formattedCurrency(amount: cost, currency: Request.shared.currency!)

    }

    map.delegate = self

    map.layoutMargins = UIEdgeInsets(top: 50, left: 0, bottom: 300, right: 0)

    let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.regular)

    let blurEffectView = UIVisualEffectView(effect: blurEffect)

    blurEffectView.frame = backgroundView.bounds

    blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

    backgroundView.addSubview(blurEffectView)

    let maskLayer = CAShapeLayer()

    maskLayer.path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 10, height: 10)).cgPath

    self.backgroundView.layer.mask = maskLayer

    locationManager.delegate = self

    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters

    locationManager.distanceFilter = 50

    locationManager.allowsBackgroundLocationUpdates = true

    locationManager.pausesLocationUpdatesAutomatically = false

    locationManager.activityType = .automotiveNavigation

    locationManager.requestAlwaysAuthorization()

    locationManager.startUpdatingLocation()

    self.navigationItem.hidesBackButton = true

    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.onEachSecond), userInfo: nil, repeats: true)

  }

   

  override func viewDidAppear(_ animated: Bool) {

    super.viewDidAppear(animated)

    self.requestRefresh()

  }

   

  @IBAction func onStartTapped(_ sender: UIButton) {

    Start().execute() { result in

      switch result {

      case .success(let response):

        Request.shared = response

        self.refreshScreen()

         

      case .failure(let error):

        error.showAlert()

      }

    }

  }

   

  @IBAction func onFinishTapped(_ sender: UIButton) {

    if Request.shared.confirmationCode != nil {

      showConfirmationDialog()

    }

    if route.count > 2 {

      Request.shared.log = MapsUtil.encode(items: MapsUtil.simplify(items: route, tolerance: 50))

    }

    let f = FinishService(cost: Request.shared.costBest!, log: Request.shared.log, distance: Request.shared.distanceReal!)

    finishTravel(finishService: f)

  }

   

  func showConfirmationDialog() {

    let question = UIAlertController(title: "Confirmation", message: "Finishing this service needs confirmation code delivered to user. Please enter it in following field:", preferredStyle: .alert)

    question.addAction(UIAlertAction(title: "OK", style: .default) { action in

      let code = question.textFields![0].text!

      let f = FinishService(cost: Request.shared.costBest!, distance: Request.shared.distanceReal!, confirmationCode: Int(code)!)

      self.finishTravel(finishService: f)

    })

    question.addTextField() { textField in

      textField.placeholder = "code"

    }

    self.present(question, animated: true)

  }

   

  func finishTravel(finishService: FinishService) {

    timer.invalidate()

    Finish(confirmationCode: finishService.confirmationCode, distance: finishService.distance ?? 0, log: finishService.log ?? "").execute() { result in

      switch result {

      case .success(let response):

        Request.shared.status = response.status ? Request.Status.Finished : Request.Status.WaitingForPostPay

        if response.status {

          let alert = UIAlertController(title: "Message", message: "Le paiement a été réglé et le crédit a été ajouté à votre portefeuille.", preferredStyle: .alert)

          alert.addAction(UIAlertAction(title: "OK", style: .default) { action in

            self.navigationController?.popViewController(animated: true)

          })

          self.present(alert, animated: true)

        } else {

          let vc = Bundle.main.loadNibNamed("WaitingForPayment", owner: self, options: nil)?.first as! WaitingForPaymentViewController

          vc.onDone = { b in

            self.requestRefresh()

          }

          self.present(vc, animated: true)

        }

         

      case .failure(let error):

        if error.status == ErrorStatus.ConfirmationCodeRequired {

          self.showConfirmationDialog()

        } else {

          error.showAlert()

        }

      }

    }

  }

   

  @IBAction func onButtonArrivedTapped(_ sender: ColoredButton) {

    Arrived().execute() { result in

      switch result {

      case .success(let response):

        Request.shared = response

        self.refreshScreen()

         

      case .failure(let error):

        error.showAlert()

      }

    }

  }

   

  @IBAction func onMessageTapped(_ sender: UIButton) {

    let vc = ChatViewController()

    vc.sender = Request.shared.rider!

    self.navigationController!.pushViewController(vc, animated: true)

  }

   

  @IBAction func onCancelTapped(_ sender: UIButton) {

    Cancel().execute() { result in

      switch result {

      case .success(_):

        Request.shared.status = .DriverCanceled

        self.refreshScreen()

         

      case .failure(let error):

        error.showAlert()

      }

    }

  }

   

  @objc private func requestRefresh() {

    GetCurrentRequestInfo().execute() { result in

      switch result {

      case .success(let response):

        Request.shared = response.request

        self.refreshScreen()

         

      case .failure(_):

        DialogBuilder.alertOnSuccess(message: "Done!")

        self.navigationController?.popViewController(animated: true)

      }

    }

  }

   

  private func refreshScreen(travel: Request = Request.shared) {

    switch travel.status! {

    case .RiderCanceled, .DriverCanceled:

      let alert = UIAlertController(title: "Succés", message: "La course a été annulé.", preferredStyle: .alert)

      alert.addAction(UIAlertAction(title: "OK !", style: .default) { action in

        self.navigationController?.popViewController(animated: true)

      })

      present(alert, animated: true)

      break;

       

    case .DriverAccepted:

      buttonFinish.isHidden = true

      buttonStart.isHidden = true

      let ann = MKPointAnnotation()

      ann.coordinate = travel.points[0]

      ann.title = travel.addresses[0]

      pointAnnotations.append(ann)

      map.addAnnotation(ann)

      if map.annotations.count > 1 {

        map.showAnnotations(map.annotations, animated: true)

      } else {

        map.setCenter(map.annotations[0].coordinate, animated: true)

      }

      break;

       

    case .Arrived:

      buttonStart.isHidden = false

      buttonArrived.isHidden = true

       

    case .Started:

      buttonMessage.isHidden = true

      buttonCall.isHidden = true

      buttonCancel.isHidden = true

      buttonStart.isHidden = true

      buttonFinish.isHidden = false

      buttonArrived.isHidden = true

      if pointAnnotations.count > 0 {

        for point in pointAnnotations {

          map.removeAnnotation(point)

        }

      }

      for (index, point) in travel.points.dropFirst().enumerated() {

        let ann = MKPointAnnotation()

        ann.coordinate = point

        ann.title = travel.addresses[index]

        pointAnnotations.append(ann)

        map.addAnnotation(ann)

      }

      if map.annotations.count > 1 {

        map.showAnnotations(map.annotations, animated: true)

      } else {

        map.setCenter(map.annotations[0].coordinate, animated: true)

      }

      break;

       

    case .WaitingForPostPay:

      let vc = Bundle.main.loadNibNamed("WaitingForPayment", owner: self, options: nil)?.first as! WaitingForPaymentViewController

      vc.onDone = { b in

        self.requestRefresh()

      }

      self.present(vc, animated: true)

       

       

    case .Finished, .WaitingForReview:

      DialogBuilder.alertOnSuccess(message: "Paid!")

      self.navigationController?.popViewController(animated: true)

       

    default:

      let alert = UIAlertController(title: "Error", message: "Unkown Status: \(travel.status!.rawValue)", preferredStyle: .alert)

      alert.addAction(UIAlertAction(title: "Allright!", style: .default) { action in

        self.navigationController?.popViewController(animated: true)

      })

      self.present(alert, animated: true)

    }

  }

   

  @objc func travelCanceled() {

    Request.shared.status = .RiderCanceled

    refreshScreen()

  }

   

  enum MarkerType: String {

    case pickup = "pickup"

    case dropoff = "dropOff"

    case driver = "driver"

  }

   

  func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    guard let annotation = annotation as? MKPointAnnotation else { return nil }

    let identifier = pointAnnotations.contains(annotation) ? MarkerType.dropoff : MarkerType.driver

    var view: MKMarkerAnnotationView

    if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier.rawValue) as? MKMarkerAnnotationView {

      dequeuedView.annotation = annotation

      view = dequeuedView

    } else {

      view = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifier.rawValue)

      switch(identifier) {

      case .pickup:

        view.glyphImage = UIImage(named: "annotation_glyph_home")

        view.markerTintColor = UIColor(hex: 0x009688)

        view.canShowCallout = true

        let button = UIButton(type: .detailDisclosure)

        button.addTarget(self, action: #selector(annotationTapped), for: UIControl.Event.touchUpInside)

        view.rightCalloutAccessoryView = button

        break;

         

      case .dropoff:

        view.markerTintColor = UIColor(hex: 0xFFA000)

        view.canShowCallout = true

        let button = UIButton(type: .detailDisclosure)

        button.addTarget(self, action: #selector(annotationTapped), for: UIControl.Event.touchUpInside)

        view.rightCalloutAccessoryView = button

        break;

         

      default:

        view.glyphImage = UIImage(named: "annotation_glyph_car")

      }

    }

    return view

  }

   

  @objc func annotationTapped() {

    openNavigationMenu(location: map.selectedAnnotations.last!.coordinate)

  }

   

  func openNavigationMenu(location: CLLocationCoordinate2D) {

    let alert = UIAlertController(title: "Navigation", message: "Sélectionnez l'application avec laquelle vous souhaitez naviguer", preferredStyle: .actionSheet)

    alert.addAction(UIAlertAction(title: "Apple Maps", style: .default, handler: { action in

      if let url = URL(string: "http://maps.apple.com/?q=\(location.latitude),\(location.longitude)&z=10&t=s"),

        UIApplication.shared.canOpenURL(url) {

        UIApplication.shared.open(url)

      }

    }))

    alert.addAction(UIAlertAction(title: "Google Maps", style: .default, handler: { action in

      if let url = URL(string: "comgooglemaps://?daddr=\(location.latitude),\(location.longitude)&directionsmode=driving"),

        UIApplication.shared.canOpenURL(URL(string: "comgooglemaps://")!) {

        UIApplication.shared.open(url)

      }

    }))

    alert.addAction(UIAlertAction(title: "Waze", style: .default, handler: { action in

      if let url = URL(string: "https://www.waze.com/ul?ll=\(location.latitude),\(location.longitude)&navigate=yes"),

        UIApplication.shared.canOpenURL(url) {

        UIApplication.shared.open(url)

      }

    }))

    alert.addAction(UIAlertAction(title: "Yandex.Maps", style: .default, handler: { action in

      if let url = URL(string: "yandexmaps://maps.yandex.com/?ll=\(location.latitude),\(location.longitude)&z=12"),

        UIApplication.shared.canOpenURL(URL(string: "yandexmaps://")!) {

        UIApplication.shared.open(url)

      }

       

    }))

    alert.addAction(UIAlertAction(title: "Annuler", style: .cancel, handler: nil))

    self.present(alert, animated: true, completion: nil)

  }

   

  @objc func onEachSecond() {

    let now = Date()

    let etaInterval = Request.shared.startTimestamp != nil ? (Request.shared.startTimestamp! / 1000) + Double(Request.shared.durationBest!) : Request.shared.etaPickup! / 1000

    let etaTime = Date(timeIntervalSince1970: etaInterval)

    if etaTime <= now {

      labelTime.text = NSLocalizedString("Soon!", comment: "When driver is coming later than expected.")

    } else {

      let formatter = DateComponentsFormatter()

      formatter.allowedUnits = [.minute, .second]

      formatter.unitsStyle = .short

      labelTime.text = formatter.string(from: now, to: etaTime)

    }

    recalculateCost()

     

  }

   

  func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let userLocation:CLLocation = locations[0] as CLLocation

    if route.count > 0 {

      let distance = Int(userLocation.distance(from: CLLocation(latitude: route[route.count - 1].latitude, longitude: route[route.count - 1].longitude)))

      Request.shared.distanceReal! += distance

    } else {

      route.append(userLocation.coordinate)

      Request.shared.distanceReal = 0

    }

    LocationUpdate(jwtToken: UserDefaultsConfig.jwtToken!, location: userLocation.coordinate, inTravel: true).execute() { _ in

       

    }

    route.append(userLocation.coordinate)

    driverMarker.coordinate = userLocation.coordinate

    map.addAnnotation(driverMarker)

    map.showAnnotations(pointAnnotations, animated: true)

  }

   

  func recalculateCost() {

    if let service = Request.shared.service , service.feeEstimationMode == .Dynamic {

      var cost = 0.0

      if Request.shared.status == Request.Status.Started {

        let duration = (Date().timeIntervalSince1970 - (Double(Request.shared.startTimestamp!) / 1000)) / 60

        cost = service.baseFare + (distance / 100 * service.perHundredMeters) + (duration * service.perMinuteDrive)

      }

      labelCost.text = String(format: "~\(MyLocale.formattedCurrency(amount: cost, currency: Request.shared.currency!))")

    }

  }

   

  @IBAction func onCallTouched(_ sender: UIButton) {

    if let call = Request.shared.rider?.mobileNumber,

      let url = URL(string: "tel://\(call)"),

      UIApplication.shared.canOpenURL(url) {

        UIApplication.shared.open(url)

    }

  }

}

Et voici le code pour l’app chauffeur :


import Kingfisher

import MapKit



class TravelViewController: UIViewController, CouponsViewDelegate, MKMapViewDelegate {

  @IBOutlet weak var map: MKMapView!

  @IBOutlet weak var labelCost: UILabel!

  @IBOutlet weak var labelTime: UILabel!

  @IBOutlet weak var buttonCall: ColoredButton!

  @IBOutlet weak var buttonMessage: ColoredButton!

  @IBOutlet weak var buttonCancel: ColoredButton!

  @IBOutlet weak var buttonPay: ColoredButton!

   

  var pickupMarker = MKPointAnnotation()

  var destinationMarkers: [MKPointAnnotation] = []

  var driverMarker = MKPointAnnotation()

  var timer: Timer!

  @IBOutlet weak var confirmationBarButton: UIBarButtonItem!

  @IBOutlet weak var tabBar: UISegmentedControl!

  @IBOutlet weak var backgroundView: UIView!

  @IBOutlet weak var viewStatistics: UIView!

  @IBOutlet weak var viewDriver: UIStackView!

  @IBOutlet weak var textDriverName: UILabel!

  @IBOutlet weak var textPlateNumber: UILabel!

  @IBOutlet weak var imgDriver: UIImageView!

   

  override func viewDidLoad() {

    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(self.onArrived), name: .arrived, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(self.onServiceStarted), name: .serviceStarted, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(self.onServiceCanceled), name: .serviceCanceled, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(self.onServiceFinished), name: .serviceFinished, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(self.onTravelInfoReceived), name: .travelInfoReceived, object: nil)

    NotificationCenter.default.addObserver(self, selector:#selector(self.requestRefresh), name: .connectedAfterForeground, object: nil)

    textDriverName.text = "\(Request.shared.driver?.firstName ?? "- ") \(Request.shared.driver?.lastName ?? "")"

    var details = [String]()

    if let carName = Request.shared.driver?.car?.title {

      details.append(carName)

    }

    if let carColor = Request.shared.driver?.carColor {

      details.append(carColor)

    }

    if let carPlate = Request.shared.driver?.carPlate {

      details.append(carPlate)

    }

    textPlateNumber.text = details.joined(separator: ", ")

    tabBar.addTarget(self, action: #selector(selectedTabItem), for: .valueChanged)

    map.layoutMargins = UIEdgeInsets(top: 50, left: 0, bottom: 290, right: 0)

    let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.regular)

    let blurEffectView = UIVisualEffectView(effect: blurEffect)

    blurEffectView.frame = backgroundView.bounds

    blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

    backgroundView.addSubview(blurEffectView)

    let maskLayer = CAShapeLayer()

    maskLayer.path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 10, height: 10)).cgPath

    self.backgroundView.layer.mask = maskLayer

    driverMarker = MKPointAnnotation()

    map.delegate = self

    self.navigationItem.hidesBackButton = true

    if Request.shared.service?.canEnableVerificationCode == false {

      self.navigationItem.rightBarButtonItem = nil

    }

    if var cost = Request.shared.costBest {

      if let coupon = Request.shared.coupon {

        cost = cost * Double(100 - coupon.discountPercent!) / 100

        cost = cost - Double(coupon.discountFlat!)

      }

      if let service = Request.shared.service, (service.feeEstimationMode == .Dynamic || service.feeEstimationMode == .RangedStrict || service.feeEstimationMode == .Ranged) {

        self.labelCost.text = "~\(MyLocale.formattedCurrency(amount: cost, currency: Request.shared.currency!))"

      } else {

        self.labelCost.text = MyLocale.formattedCurrency(amount: cost, currency: Request.shared.currency!)

      }

    }

    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.onEachSecond), userInfo: nil, repeats: true)

  }

   

  @objc func selectedTabItem(sender: UISegmentedControl) {

    if sender.selectedSegmentIndex == 1 {

      viewDriver.isHidden = true

      viewStatistics.isHidden = false

    } else {

      viewDriver.isHidden = false

      viewStatistics.isHidden = true

    }

  }

   

  @IBAction func onMessageTapped(_ sender: UIButton) {

    let vc = ChatViewController()

    vc.sender = Request.shared.driver!

    self.navigationController!.pushViewController(vc, animated: true)

  }

   

  override func viewDidAppear(_ animated: Bool) {

    super.viewDidAppear(animated)

    self.requestRefresh()

  }

   

  @objc func onEachSecond() {

    let now = Date()

    let etaInterval = Request.shared.startTimestamp != nil ? (Request.shared.startTimestamp! / 1000) + Double(Request.shared.durationBest!) : Request.shared.etaPickup! / 1000

    let etaTime = Date(timeIntervalSince1970: etaInterval)

    if etaTime <= now {

      if Request.shared.status == .Arrived {

        labelTime.text = NSLocalizedString("Arrived!", comment: "Driver Arrived text instead of time.")

      } else {

        labelTime.text = NSLocalizedString("Soon!", comment: "When driver is coming later than expected.")

      }

       

    } else {

      let formatter = DateComponentsFormatter()

      formatter.allowedUnits = [.minute, .second]

      formatter.unitsStyle = .short

      labelTime.text = formatter.string(from: now, to: etaTime)

    }

  }

   

  @objc private func requestRefresh() {

    GetCurrentRequestInfo().execute() { result in

      switch result {

      case .success(let response):

        Request.shared = response.request

        self.refreshScreen(driverLocation: response.driverLocation)

         

      case .failure(_):

        self.navigationController?.popViewController(animated: false)

      }

    }

  }

   

  private func refreshScreen(travel: Request = Request.shared, driverLocation: CLLocationCoordinate2D?) {

    if let driverImage = travel.driver?.media?.address {

      let processor = DownsamplingImageProcessor(size: imgDriver.intrinsicContentSize) |> RoundCornerImageProcessor(cornerRadius: imgDriver.intrinsicContentSize.width / 2)

      let url = URL(string: Config.Backend + driverImage.replacingOccurrences(of: " ", with: "%20"))

      imgDriver.kf.setImage(with: url, placeholder: UIImage(named: "Nobody"), options: [

        .processor(processor),

        .scaleFactor(UIScreen.main.scale),

        .transition(.fade(0.5)),

        .cacheOriginalImage

      ]) { result in

        switch result {

        case .success(let value):

          print("Task done for: \(value.source.url?.absoluteString ?? "")")

        case .failure(let error):

          print("Job failed: \(error.localizedDescription)")

        }

      }

    }

    switch travel.status! {

    case .RiderCanceled, .DriverCanceled:

      let alert = UIAlertController(title: "Succés", message: "La course a été annulé.", preferredStyle: .alert)

      alert.addAction(UIAlertAction(title: "OK!", style: .default) { action in

        _ = self.navigationController?.popViewController(animated: true)

      })

      present(alert, animated: true)

      break

       

    case .DriverAccepted:

      pickupMarker.coordinate = travel.points[0]

      map.addAnnotation(pickupMarker)

      if let _location = driverLocation {

        driverMarker.coordinate = _location

        map.addAnnotation(driverMarker)

        map.showAnnotations([pickupMarker, driverMarker], animated: true)

      } else {

        let region = MKCoordinateRegion(center: travel.points[0], latitudinalMeters: 1000, longitudinalMeters: 1000)

        map.setRegion(region, animated: true)

      }

      break

       

    case .Arrived:

      DialogBuilder.alertOnSuccess(message: NSLocalizedString("Driver Arrived", comment: "Alert for driver Arrival"))

      break

       

    case .Started:

      buttonCall.isHidden = true

      buttonMessage.isHidden = true

      buttonCancel.isHidden = true

      map.removeAnnotation(pickupMarker)

      for (index, point) in travel.points.enumerated() {

        if index == 0 {

          continue;

        }

        let p = MKPointAnnotation()

        p.coordinate = point

        destinationMarkers.append(p)

        map.addAnnotation(p)

      }

      if driverLocation != nil || destinationMarkers.count > 1 {

        if(driverLocation != nil) {

          driverMarker.coordinate = driverLocation!

          map.addAnnotation(driverMarker)

          destinationMarkers.append(driverMarker)

          map.showAnnotations(destinationMarkers, animated: true)

          destinationMarkers.removeLast()

        } else {

          map.showAnnotations(destinationMarkers, animated: true)

        }

      } else {

        let region = MKCoordinateRegion(center: travel.points[1], latitudinalMeters: 1000, longitudinalMeters: 1000)

        map.setRegion(region, animated: true)

      }

      break

       

    case .WaitingForPostPay:

      if travel.service?.paymentMethod == .OnlyCash {

        let alert = UIAlertController(title: "Payment", message: "Service Has Been finished and payment is waiting to be settled.", preferredStyle: .alert)

        alert.addAction(UIAlertAction(title: "Done!", style: .default) { action in

          self.requestRefresh()

        })

      } else {

        if let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Wallet") as? WalletViewController {

          vc.amount = Request.shared.costAfterCoupon

          vc.currency = Request.shared.currency

          self.navigationController?.pushViewController(vc, animated: true)

        }

      }

       

      break

       

       

    case .WaitingForReview:

      let storyboard = UIStoryboard(name: "Main", bundle: nil)

      let controller = storyboard.instantiateViewController(withIdentifier: "finishedViewController")

      self.navigationController?.pushViewController(controller, animated: false)

      break

       

    case .Finished:

      DialogBuilder.alertOnSuccess(message: "Done!")

      self.navigationController?.popViewController(animated: true)

       

    default:

      let alert = UIAlertController(title: "Error", message: "Unknown status: \(travel.status!.rawValue)", preferredStyle: .alert)

      alert.addAction(UIAlertAction(title: "Allright!", style: .default) { action in

        _ = self.navigationController?.popViewController(animated: true)

      })

      self.present(alert, animated: true)

    }

  }

   

  @IBAction func onCancelTapped(_ sender: UIButton) {

    Cancel().execute() { result in

      switch result {

      case .success(_):

        Request.shared.status = .RiderCanceled

        self.refreshScreen(driverLocation: nil)

         

      case .failure(let error):

        error.showAlert()

      }

    }

  }

   

  @IBAction func onWalletTapped(_ sender: UIButton) {

    buttonPay.isHidden = true

    if let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Wallet") as? WalletViewController {

      vc.amount = Request.shared.costAfterCoupon

      vc.currency = Request.shared.currency

      self.navigationController!.pushViewController(vc, animated: true)

    }

  }

   

  @objc func onServiceStarted(_ notification: Notification) {

    Request.shared = notification.object as! Request

    let location = driverMarker.coordinate.latitude != 0 ? driverMarker.coordinate : nil

    refreshScreen(driverLocation: location)

  }

   

  @objc func onArrived(_ notification: Notification) {

    Request.shared = notification.object as! Request

    refreshScreen(driverLocation: nil)

  }

   

  @objc func onServiceCanceled(_ notification: Notification) {

    Request.shared.status = .DriverCanceled

    refreshScreen(driverLocation: nil)

  }

   

  @objc func onServiceFinished(_ notification: Notification) {

    let obj = notification.object as! [Any]

    Request.shared.status = (obj[0] as! Bool) == true ? Request.Status.WaitingForReview : Request.Status.WaitingForPostPay

    refreshScreen(driverLocation: nil)

  }

   

  @objc func onTravelInfoReceived(_ notification: Notification) {

    refreshScreen(driverLocation: (notification.object as! CLLocationCoordinate2D))

  }

   

  @IBAction func onSelectCouponClicked(_ sender: UIButton) {

    if let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CouponsCollectionViewController") as? CouponsCollectionViewController

    {

      vc.selectMode = true

      vc.delegate = self

      self.navigationController!.pushViewController(vc, animated: true)

    }

  }

   

  func didSelectedCoupon(_ coupon: Coupon) {

    ApplyCoupon(code: coupon.code!).execute() { result in

      switch result {

      case .success(let response):

        DialogBuilder.alertOnSuccess(message: "Done!")

        if let service = Request.shared.service, (service.feeEstimationMode == .Dynamic || service.feeEstimationMode == .RangedStrict || service.feeEstimationMode == .Ranged) {

          self.labelCost.text = "~\(MyLocale.formattedCurrency(amount: response, currency: Request.shared.currency!))"

        } else {

          self.labelCost.text = MyLocale.formattedCurrency(amount: response, currency: Request.shared.currency!)

        }

         

      case .failure(let error):

        error.showAlert()

      }

    }

  }

   

  enum MarkerType: String {

    case pickup = "pickup"

    case dropoff = "dropOff"

    case driver = "driver"

  }

   

  func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    guard let annotation = annotation as? MKPointAnnotation else { return nil }

    let identifier = annotation == pickupMarker ? MarkerType.pickup : (annotation == driverMarker ? MarkerType.driver : MarkerType.dropoff)

    var view: MKMarkerAnnotationView

    if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier.rawValue) as? MKMarkerAnnotationView {

      dequeuedView.annotation = annotation

      view = dequeuedView

    } else {

      view = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifier.rawValue)

      switch(identifier) {

      case .pickup:

        view.glyphImage = UIImage(named: "annotation_glyph_home")

        view.markerTintColor = UIColor(hex: 0x009688)

        break;

         

      case .dropoff:

        view.markerTintColor = UIColor(hex: 0xFFA000)

        break;

         

      default:

        view.glyphImage = UIImage(named: "annotation_glyph_car")

      }

    }

    return view

  }

   

  @IBAction func onCallTouched(_ sender: UIButton) {

    if let call = Request.shared.driver?.mobileNumber, let url = URL(string: "tel://\(call)"), UIApplication.shared.canOpenURL(url) {

      UIApplication.shared.open(url)

    }

  }

   

  @IBAction func enableConfirmationClicked(_ sender: UIBarButtonItem) {

    EnableVerification().execute() { result in

      switch result {

      case .success(let response):

        let message = UIAlertController(title: "Done", message: "Confirmation code service is enabled. Driver will need to enter \(response) to finish service.", preferredStyle: .alert)

        message.addAction(UIAlertAction(title: "OK", style: .default))

        self.present(message, animated: true)

         

      case .failure(let error):

        error.showAlert()

      }

    }

  }

}

Thanks for participating! We take our Code of Conduct very seriously and want to help ensure that everyone has a good experience free of antagonism and harassment. Unfortunately, we don’t currently have moderators for languages other than English. What this means is that, until that changes, we need to ask that everyone use English here in the GitHub Community Forum when posting. We’ll be locking any posts in languages other than English for now, including this one.

Thanks for meeting us halfway :grinning: