user8485597 user8485597 - 1 month ago 11
Swift Question

Trouble storing user location in Swift3

What I want to do is pass the user location to complete my JSON URL. But the way I do it, it prints "optional(coordinate)" and I just want the coordinate wihtout the optional. I tried to erase

?
but it would mark error at the moment to build.

I tried to get the user location in the
func locationManager
and I try to use them in the
func loadGas
. Any help could be of use.

import UIKit
import MapKit
import CoreLocation

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
}
}

@IBOutlet var mapa: MKMapView!
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
print(myLocation)
let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
mapa.setRegion(region, animated: true)
self.mapa.showsUserLocation = true
manager.stopUpdatingLocation()
}

override func viewDidLoad() {
super.viewDidLoad()

//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 lat = String(describing: manager.location?.coordinate.latitude)
let long = String(describing: manager.location?.coordinate.longitude)

let url = URL(string: "http://192.241.214.56/api/ubicacion/?format=json&sub="+lat+","+long)
print (url)

// let url = URL(string: "http://192.241.214.56/api/ubicacion/?format=json&sub=29.08919%2C-110.96133")
// 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)
}
}

Answer Source

Instead of

let lat = String(describing: manager.location?.coordinate.latitude)

you should do something like this:

guard let location = manager.location else {
    return
}
let lat = String(format: "%f", location.coordinate.latitude)