我想用來自 API 的資料替換緯度和經度,我只是不知道如何從 MapViewController 呼叫它們,所有這些都設定了如何從我創建并與 APICaller.swift 連接的結構中呼叫它們
Vehicles.swift 結構:
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?
}
現在我需要將緯度和經度放在“另一個視圖控制器”中:
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
uj5u.com熱心網友回復:
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)
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/364965.html
上一篇:停止按鈕單擊后執行的計時器
