I'm making an app that should load all the gas stations and their prices on the state. The map should reload the prices if the user selects a diferent type of gas (Magna, Premium and Diesel). This is made through a UISegment control.
The trouble is that when I reload the map it doesn't print the correct price (the default one is magna, and when I select the other type of gas it doesn't load the new prices).
This is my code.
class MapViewController: UIViewController,MKMapViewDelegate, CLLocationManagerDelegate,UICollectionViewDelegate, UICollectionViewDataSource {
let manager = CLLocationManager()
public let sMAGNA = "magna"
public let sPREMIUM = "premium"
public let sDIESEL = "diesel"
public let MIN_TIME: CLong = 400
private let MIN_DISTANCE: Float = 1000
private var ubicaciones_selected: [Ubicacion] = []
private var ubicaciones_magna: [Ubicacion] = []
private var ubicaciones_premium: [Ubicacion] = []
private var ubicaciones_diesel: [Ubicacion] = []
private let REQUEST_LOCATION = 1
private var latlon: String = ""
private var mType: String = "magna"
var ubicaciones:[Ubicacion] = []
var Ubigaspin = MKPointAnnotation()
@IBAction func MapType(_ sender: Any) {
if mapa.mapType == MKMapType.standard{
mapa.mapType = MKMapType.satellite
} else {
mapa.mapType = MKMapType.standard
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.mapa.delegate = self
//con esto obtendremos la ubicacion del usuario
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
mapa.showsUserLocation = true
manager.startUpdatingLocation()
//se cargan los pines y las gasolinas
loadGas(tipo: mType)
}
func loadGas(tipo:String){
mType = tipo
var ubicaciones:[Ubicacion] = []
switch tipo {
case sMAGNA:
ubicaciones = ubicaciones_magna
case sPREMIUM:
ubicaciones = ubicaciones_premium
case sDIESEL:
ubicaciones = ubicaciones_diesel
default:
ubicaciones = ubicaciones_magna
}
if ubicaciones.count == 0 {
let url = URL(string: "http://192.241.214.56/api/"+tipo+"/?format=json")
URLSession.shared.dataTask(with: url!, completionHandler: {
(data, response, error) in
if(error != nil){
print("error")
}else{
do{
let ubicaciones_json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [[String : AnyObject]]
for ubicacion in ubicaciones_json{
let nombre:String = ubicacion["nombre"] as! String
let direccion:String = ubicacion["direccion"] as! String
let precio_magna:Float = ubicacion["precio_magna"] as! Float
let precio_premium:Float = ubicacion["precio_premium"] as! Float
let precio_diesel:Float = ubicacion["precio_diesel"] as! Float
let ubicacion:String = ubicacion["ubicacion"] as! String
let p = Ubicacion()
p.ubicacion = ubicacion
p.setLatLng()
p.nombre = nombre
p.direccion = direccion
p.precio_magna = precio_magna
p.precio_premium = precio_premium
p.precio_diesel = precio_diesel
ubicaciones.append(p)
}
self.ubicaciones = ubicaciones
OperationQueue.main.addOperation({
self.updatePins(ubicaciones: ubicaciones)
})
}catch let error as NSError{
print(error)
}
}
}).resume()
}else{
self.ubicaciones = ubicaciones
self.updatePins(ubicaciones: ubicaciones)
}
}
func updatePins(ubicaciones:[Ubicacion]){
mapa.removeAnnotations(mapa.annotations)
for ubicacion in ubicaciones{
let anno = CustonAnno(ubicacion:ubicacion, image: #imageLiteral(resourceName: "icon"))
anno.coordinate = CLLocationCoordinate2D(latitude: ubicacion.latitude!, longitude: ubicacion.longitude!)
anno.title=ubicacion.nombre
//anno.subtitle="$\(ubicacion.getPrecio(tipo: mType))"
self.mapa.addAnnotation(anno)
}
}
@IBAction func changeSegment(_ sender: UISegmentedControl) {
print(sender.selectedSegmentIndex)
switch sender.selectedSegmentIndex {
case 0:
loadGas(tipo: sMAGNA)
case 1:
loadGas(tipo: sPREMIUM)
case 2:
loadGas(tipo: sDIESEL)
default:
loadGas(tipo: sMAGNA)
}
}
}
I think your problem is with your ubicaciones
vars, you have a local var and a instance var with the same name, you need work all the time with your instance var instead of create another, you are also losing your information over and over again making your network calls needed every time you change your gas type
Try replacing your loadGas
method
by this one
func loadGas(tipo:String){
mType = tipo
switch tipo {
case sMAGNA:
if(ubicaciones_magna.count > 0){
self.ubicaciones = ubicaciones_magna
self.updatePins(ubicaciones: self.ubicaciones)
return
}
case sPREMIUM:
if(ubicaciones_premium.count > 0){
self.ubicaciones = ubicaciones_premium
self.updatePins(ubicaciones: self.ubicaciones)
return
}
case sDIESEL:
if(ubicaciones_diesel.count > 0){
self.ubicaciones = ubicaciones_diesel
self.updatePins(ubicaciones: self.ubicaciones)
return
}
default:
if(ubicaciones_magna.count > 0){
self.ubicaciones = ubicaciones_magna
self.updatePins(ubicaciones: self.ubicaciones)
return
}
}
let url = URL(string: "http://192.241.214.56/api/"+tipo+"/?format=json")
URLSession.shared.dataTask(with: url!, completionHandler: {
(data, response, error) in
if(error != nil){
print("error")
}else{
do{
let ubicaciones_json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [[String : AnyObject]]
var newUbications:[Ubicacion] = []
for ubicacion in ubicaciones_json{
let nombre:String = ubicacion["nombre"] as! String
let direccion:String = ubicacion["direccion"] as! String
let precio_magna:Float = ubicacion["precio_magna"] as! Float
let precio_premium:Float = ubicacion["precio_premium"] as! Float
let precio_diesel:Float = ubicacion["precio_diesel"] as! Float
let ubicacion:String = ubicacion["ubicacion"] as! String
let p = Ubicacion()
p.ubicacion = ubicacion
p.setLatLng()
p.nombre = nombre
p.direccion = direccion
p.precio_magna = precio_magna
p.precio_premium = precio_premium
p.precio_diesel = precio_diesel
newUbications.append(p)
}
switch tipo {
case sMAGNA:
self.ubicaciones_magna = newUbications
self.ubicaciones = self.ubicaciones_magna
case sPREMIUM:
self.ubicaciones_premium = newUbications
self.ubicaciones = self.ubicaciones_premium
case sDIESEL:
self.ubicaciones_diesel = newUbications
self.ubicaciones = ubicaciones_diesel
default:
self.ubicaciones_magna = newUbications
self.ubicaciones = self.ubicaciones_magna
}
OperationQueue.main.addOperation({
self.updatePins(ubicaciones: self.ubicaciones)
})
}catch let error as NSError{
print(error)
}
}
}).resume()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.