I want to replace the latitude and longitude with the data coming from API, I just don't know how to call them from the MapViewController, all are set up just how to call them from the structure I created and connected with the APICaller.swift
The Vehicles.swift structure:
struct Vehicles: Codable {
var IDVehicle: Int?
var Title: String?
var RegistrationDate: String?
var ExpireDate: String?
var Department: String?
var Identification: String?
var Speed: String?
var Latitude: Double?
var Longitude: Double?
var Angle: Int?
var Status: Int?
var InputValue: Int?
var Plate: String?
var LastCommunicationDate: String?
var Passengers: Int?
var Driver: String?
}
Now I need to put the Latitude and Longtitude in here "another viewController" :
let appleHQ = CLLocation(latitude: 37.334722 , longitude: 37.334722)
let regionRadius: CLLocationDistance = 1000.0
let region = MKCoordinateRegion(center: appleHQ.coordinate, latitudinalMeters: regionRadius, longitudinalMeters: regionRadius)
mapView.setRegion(region, animated: true)
mapView.delegate = self
CodePudding user response:
class APIManager{
static var sharedInstance:APIManager = APIManager()
func apiCallerToFetchData(completion:(Result<Vehicles,Error>)->()){
//NetworkCall
//After Getting Response assign that value ,but below i put as static code
let vechicle = Vehicles(IDVehicle: 1, Title: "", RegistrationDate: "", ExpireDate: "", Department: "", Identification: "", Speed: "", Angle: 1, Status: 1, InputValue: 1, Plate: "", LastCommunicationDate: "", Passengers: 1)
completion(.success(vechicle))
}
}
class MapViewController: UIViewController {
var globalVechicle = Vehicles()
var localLattitude :Double?
var localLongitude :Double?
override func viewDidLoad() {
super.viewDidLoad()
fetchDataFromAPI {_ in
updateUIHere()
}
}
func updateUIHere(){
//you can either using globalVechicle.lattitude or localLattitude while assigning the value
guard let lattitude = globalVechicle.Latitude ,let longitude = globalVechicle.Longitude else { return }
let appleHQ = CLLocation(latitude: lattitude , longitude: longitude)
let regionRadius: CLLocationDistance = 1000.0
let region = MKCoordinateRegion(center: appleHQ.coordinate, latitudinalMeters: regionRadius, longitudinalMeters: regionRadius)
mapView.setRegion(region, animated: true)
mapView.delegate = self
}
func fetchDataFromAPI(completion:(Bool)->()){
APIManager.sharedInstance.apiCallerToFetchData { result in
switch result{
case .success(let vechicle):
globalVechicle = vechicle
localLattitude = vechicle.Latitude
localLongitude = vechicle.Longitude
completion(true)
case .failure(let Error)
completion(false)
}
}
}
}