无法在Swift3中存储用户位置

时间:2017-08-23 20:56:35

标签: ios swift core-location

我想要做的是传递用户位置以完成我的JSON URL。但是我这样做的方式是打印"可选(坐标)"我只想要与可选的坐标。我试图删除?,但它会标记当前的错误。

我尝试在func locationManager中获取用户位置,并尝试在func loadGas中使用它们。任何帮助都可以使用。

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

1 个答案:

答案 0 :(得分:0)

而不是

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

你应该这样做:

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