Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/120.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios CLLocationManager总是崩溃并返回零值_Ios_Swift_Xcode_Core Location_Cllocationmanager - Fatal编程技术网

Ios CLLocationManager总是崩溃并返回零值

Ios CLLocationManager总是崩溃并返回零值,ios,swift,xcode,core-location,cllocationmanager,Ios,Swift,Xcode,Core Location,Cllocationmanager,我已经用swift构建了一个iOS应用程序 我在我的应用程序中实现了核心位置和地图视图。这是第一次,它可以顺利运行而没有任何问题(在模拟器或iPhone上) 该应用程序可以正常工作,并且可以从我的iPhone获取当前位置。但是,当我尝试在Xcode中添加GPX位置时,一切都会发生变化(我想尝试在GPX文件中使用任何位置)。添加GPX文件并将其选择为模拟器位置后,我的应用程序总是崩溃,CLLocationManager总是返回nil值 我认为这个问题只存在于模拟器中,但我的iPhone也出现了。即

我已经用swift构建了一个iOS应用程序

我在我的应用程序中实现了核心位置和地图视图。这是第一次,它可以顺利运行而没有任何问题(在模拟器或iPhone上)

该应用程序可以正常工作,并且可以从我的iPhone获取当前位置。但是,当我尝试在Xcode中添加GPX位置时,一切都会发生变化(我想尝试在GPX文件中使用任何位置)。添加GPX文件并将其选择为模拟器位置后,我的应用程序总是崩溃,CLLocationManager总是返回nil值

我认为这个问题只存在于模拟器中,但我的iPhone也出现了。即使我删除了GPX文件,问题仍然存在

每当我想得到纬度和经度值时,我总是得到一条“EXC_BAD_指令”

这是我的代码:

let corLoc = CLLocationManager()

    //let corLoc2 = CLLocationManager()


    corLoc.delegate = self
    let statusLoc = CLLocationManager.authorizationStatus()
    if statusLoc == .notDetermined{
        corLoc.requestWhenInUseAuthorization()
    }
    corLoc.desiredAccuracy = kCLLocationAccuracyBest

    corLoc.startUpdatingLocation()

    let lokasiAwal = CLLocationCoordinate2D(latitude: (corLoc.location?.coordinate.latitude)!, longitude: (corLoc.location?.coordinate.longitude)!) //<--- always return EXC_BAD_INSTRUCTION


    let lokasiAkhir = CLLocationCoordinate2D(latitude: -7.299356, longitude: 112.676108)
}

这是我的点注释类

class MyPointAnnotation : MKPointAnnotation {
var pinTintColor: UIColor?

}

viewdidload
中使用CoreLocation委托&在
didUpdateLocations

import UIKit
import CoreLocation

class ViewController: UIViewController,CLLocationManagerDelegate {

    let corLoc = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        corLoc.delegate = self
        let statusLoc = CLLocationManager.authorizationStatus()
        if statusLoc == .notDetermined{
            corLoc.requestWhenInUseAuthorization()
        }
        corLoc.desiredAccuracy = kCLLocationAccuracyBest
        corLoc.startUpdatingLocation()

    }
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
      print((corLoc.location?.coordinate.latitude) ?? "No values")
        let lokasiAwal = CLLocationCoordinate2D(latitude: (corLoc.location?.coordinate.latitude)!, longitude: (corLoc.location?.coordinate.longitude)!) //
        let lokasiAkhir = CLLocationCoordinate2D(latitude: -7.299356, longitude: 112.676108)
    }

}

你的问题是,
CLLocationManager
可能还没有任何职位。当数据准备就绪时,将调用委托方法
didUpdateLocations

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLocation:CLLocation = locations[0] as CLLocation
    // manager.stopUpdatingLocation()
    lokasiAwal = userLocation
}

正如我在评论中所说:您的问题是
CLLocationManager
可能还没有任何位置,因此您正在强制展开可能为零的值,在
didUpdateLocations
中,这将不再发生,因为当
CLLocationManager
定义了位置时会调用此方法

代码中的主要更改是

extension LocationViewController : CLLocationManagerDelegate
    {
        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

            if let location = locations.last
            {
                if((location.horizontalAccuracy) < CLLocationAccuracy(0))
                {
                    return
                }

                lokasiAwal2 = location

                 //Calling the method when we are sure that a position is getted
                self.updateUIAndGetDirection()
                self.corLoc.stopUpdatingLocation() //avoiding continue direction changes 
            }
        }
    }
扩展位置视图控制器:CLLocationManagerDelegate
{
func locationManager(manager:CLLocationManager,didUpdateLocations位置:[CLLocation]){
如果let location=locations.last
{
if((位置水平精度)
完整代码

import UIKit
import CoreLocation
import MapKit

class LocationViewController: UIViewController  {


    @IBOutlet weak var mapRoute: MKMapView!
    var lokasiAwal2 = CLLocation()
    var corLoc = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        mapRoute.delegate = self

        //let corLoc2 = CLLocationManager()


        corLoc.delegate = self
        let statusLoc = CLLocationManager.authorizationStatus()
        if statusLoc == .notDetermined{
            corLoc.requestWhenInUseAuthorization()
        }
        corLoc.desiredAccuracy = kCLLocationAccuracyBest

        corLoc.startUpdatingLocation()


        // Do any additional setup after loading the view.
    }


    func updateUIAndGetDirection()
    {
        //let lokasiAwal = CLLocationCoordinate2D(latitude: (corLoc.location?.coordinate.latitude)!, longitude: (corLoc.location?.coordinate.longitude)!)

        let lokasiAwal = CLLocationCoordinate2D(latitude: lokasiAwal2.coordinate.latitude, longitude: lokasiAwal2.coordinate.longitude)


        //let lokasiAwal = CLLocationCoordinate2D(latitude: -7.263056, longitude: 112.740317)

        let lokasiAkhir = CLLocationCoordinate2D(latitude: -7.299356, longitude: 112.676108)
        //-7.299356, 112.676108 NH
        //-7.289182, 112.676104 PTC
        //-7.282713, 112.687633 bandar jakarta
        //-7.263056, 112.740317 TP

        //placemark
        let awalPlaceMark = MKPlacemark(coordinate: lokasiAwal, addressDictionary: nil)
        let akhirPlaceMark = MKPlacemark(coordinate: lokasiAkhir, addressDictionary: nil)

        let awalMap = MKMapItem(placemark: awalPlaceMark)
        let akhirMap = MKMapItem(placemark: akhirPlaceMark)


        //anotasi
        let awalAnotasi = MKPointAnnotation()
        awalAnotasi.title = "Your Location"


        //let awalPin = MKPinAnnotationView.init(annotation: awalAnotasi, reuseIdentifier: "Your Location")
        //awalPin.pinTintColor = UIColor.blue


        if let locationAwal = awalPlaceMark.location {
            awalAnotasi.coordinate = locationAwal.coordinate
        }

        let akhirAnotasi = MKPointAnnotation()
        akhirAnotasi.title = "National Hospital"

        if let locationAkhir = akhirPlaceMark.location {
            akhirAnotasi.coordinate = locationAkhir.coordinate
        }

        let awalPin = MyPointAnnotation()
        awalPin.coordinate = awalAnotasi.coordinate
        awalPin.pinTintColor = .green
        awalPin.title = awalAnotasi.title

        let akhirPin = MyPointAnnotation()
        akhirPin.coordinate = akhirAnotasi.coordinate
        akhirPin.pinTintColor = .blue
        akhirPin.title = akhirAnotasi.title

        //titik marker
        self.mapRoute.showAnnotations([awalPin, akhirPin], animated: true)


        //menambahkan route
        let directionRequest = MKDirectionsRequest()
        directionRequest.source = awalMap
        directionRequest.destination = akhirMap
        directionRequest.transportType = .automobile

        let directions = MKDirections(request: directionRequest)
        directions.calculate
            {
                (response, error) -> Void in

                guard let response = response else
                {
                    if let error = error {
                        print("Error : \(error)")
                    }
                    return
                }

                let route = response.routes[0]


                self.mapRoute.add((route.polyline), level: MKOverlayLevel.aboveRoads)

                let rect = route.polyline.boundingMapRect
                self.mapRoute.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
                self.mapRoute.delegate = self

        }
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
     // MARK: - Navigation

     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
}

extension LocationViewController : MKMapViewDelegate
{
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let renderer = MKPolylineRenderer(overlay: overlay)
        renderer.lineWidth = 1.0
        renderer.strokeColor = UIColor.red

        return renderer
    }

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

        var annotView = mapView.dequeueReusableAnnotationView(withIdentifier: "myAnnotation") as? MKPinAnnotationView
        if annotView == nil {
            annotView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myAnnotation")
        }
        else {
            annotView?.annotation = annotation
        }
        if let annotation = annotation as? MyPointAnnotation {
            annotView?.pinTintColor = annotation.pinTintColor
            annotView?.canShowCallout = true
        }

        return annotView
    }

}

extension LocationViewController : CLLocationManagerDelegate
{
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        if let location = locations.last
        {
            if((location.horizontalAccuracy) < CLLocationAccuracy(0))
            {
                return
            }

            lokasiAwal2 = location

            self.updateUIAndGetDirection()
            self.corLoc.stopUpdatingLocation() //avoiding continue direction changes 
        }
    }

    func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {

        if status == CLAuthorizationStatus.authorizedWhenInUse || status == CLAuthorizationStatus.authorizedAlways {

            manager.startUpdatingLocation()

        }
    }
}
导入UIKit
导入核心定位
导入地图套件
类位置ViewController:UIViewController{
@IBVAR映射路径:MKMapView!
var lokasiAwal2=CLLocation()
var corLoc=CLLocationManager()
重写func viewDidLoad(){
super.viewDidLoad()
mapRoute.delegate=self
//设corLoc2=CLLocationManager()
corLoc.delegate=self
让statusLoc=CLLocationManager.authorizationStatus()
如果statusLoc==.notDetermined{
corLoc.requestwhenUseAuthorization()
}
corLoc.desiredAccuracy=kCLLocationAccuracyBest
corLoc.startUpdatingLocation()
//加载视图后执行任何其他设置。
}
func updateUIAndGetDirection()
{
//设lokasiAwal=CLLocationCoordinate2D(纬度:(corLoc.location?坐标.纬度)!,经度:(corLoc.location?坐标.经度)!)
设lokasiAwal=CLLocationCoordinate2D(纬度:lokasiAwal2.coordinate.lation,经度:lokasiAwal2.coordinate.longitude)
//设lokasiAwal=CLLocationCoordinate2D(纬度:-7.263056,经度:112.740317)
设lokasiAkhir=CLLocationCoordinate2D(纬度:-7.299356,经度:112.676108)
//-7.299356112.676108新罕布什尔州
//-7.289182112.676104 PTC
//-7.282713112.687633雅加达班达尔
//-7.263056112.740317 TP
//地标
let awalPlaceMark=MKPlacemark(坐标:lokasiAwal,地址字典:nil)
设akhirPlaceMark=MKPlacemark(坐标:lokasiAkhir,地址字典:nil)
让awalMap=MKMapItem(placemark:awalPlaceMark)
设akhirMap=MKMapItem(placemark:akhirPlaceMark)
//阿诺塔西
让awalAnotasi=MKPointAnnotation()
awalAnotasi.title=“您的位置”
//让awalPin=MKPinAnnotationView.init(注释:awalAnotasi,reuseIdentifier:“您的位置”)
//awalPin.pinTintColor=UIColor.blue
如果let locationAwal=awalPlaceMark.location{
awalAnotasi.coordinate=位置awal.coordina
}
设akhirAnotasi=MKPointAnnotation()
akhirAnotasi.title=“国家医院”
如果let locationAkhir=akhirPlaceMark.location{
akhirAnotasi.coordinate=位置Akhir.coordina
}
let awalPin=MyPointAnnotation()
awalPin.coordinate=awalAnotasi.coordina
awalPin.pinTintColor=.green
awalPin.title=awalAnotasi.title
设akhirPin=MyPointAnnotation()
akhirPin.coordinate=akhirAnotasi.coordinate
akhirPin.pinTintColor=.blue
akhirPin.title=akhirAnotasi.title
//提提克记号笔
self.mapRoute.showAnnotations([awalPin,akhirPin],动画:true)
//门纳巴坎路线
let directionRequest=mkdirectionrequest()
directionRequest.source=awalMap
directionRequest.destination=akhirMap
directionRequest.transportType=.automobile
let directions=MKDirections(请求:directionRequest)
方向,计算
{
(响应,错误)->在中无效
防护装置let响应=响应else
{
如果let error=error{
打印(“错误:\(错误)”)
}
返回
}
let route=response.routes[0]
self.mapproute.add((route.polyline),标高:MKOverlayLevel.overroads)
设rect=route.polyline.boundingMapRect
self.mapRoute.setRegion(mkCoordinatereRegionformaprect(rect),动画:true)
self.mapR
import UIKit
import CoreLocation
import MapKit

class LocationViewController: UIViewController  {


    @IBOutlet weak var mapRoute: MKMapView!
    var lokasiAwal2 = CLLocation()
    var corLoc = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        mapRoute.delegate = self

        //let corLoc2 = CLLocationManager()


        corLoc.delegate = self
        let statusLoc = CLLocationManager.authorizationStatus()
        if statusLoc == .notDetermined{
            corLoc.requestWhenInUseAuthorization()
        }
        corLoc.desiredAccuracy = kCLLocationAccuracyBest

        corLoc.startUpdatingLocation()


        // Do any additional setup after loading the view.
    }


    func updateUIAndGetDirection()
    {
        //let lokasiAwal = CLLocationCoordinate2D(latitude: (corLoc.location?.coordinate.latitude)!, longitude: (corLoc.location?.coordinate.longitude)!)

        let lokasiAwal = CLLocationCoordinate2D(latitude: lokasiAwal2.coordinate.latitude, longitude: lokasiAwal2.coordinate.longitude)


        //let lokasiAwal = CLLocationCoordinate2D(latitude: -7.263056, longitude: 112.740317)

        let lokasiAkhir = CLLocationCoordinate2D(latitude: -7.299356, longitude: 112.676108)
        //-7.299356, 112.676108 NH
        //-7.289182, 112.676104 PTC
        //-7.282713, 112.687633 bandar jakarta
        //-7.263056, 112.740317 TP

        //placemark
        let awalPlaceMark = MKPlacemark(coordinate: lokasiAwal, addressDictionary: nil)
        let akhirPlaceMark = MKPlacemark(coordinate: lokasiAkhir, addressDictionary: nil)

        let awalMap = MKMapItem(placemark: awalPlaceMark)
        let akhirMap = MKMapItem(placemark: akhirPlaceMark)


        //anotasi
        let awalAnotasi = MKPointAnnotation()
        awalAnotasi.title = "Your Location"


        //let awalPin = MKPinAnnotationView.init(annotation: awalAnotasi, reuseIdentifier: "Your Location")
        //awalPin.pinTintColor = UIColor.blue


        if let locationAwal = awalPlaceMark.location {
            awalAnotasi.coordinate = locationAwal.coordinate
        }

        let akhirAnotasi = MKPointAnnotation()
        akhirAnotasi.title = "National Hospital"

        if let locationAkhir = akhirPlaceMark.location {
            akhirAnotasi.coordinate = locationAkhir.coordinate
        }

        let awalPin = MyPointAnnotation()
        awalPin.coordinate = awalAnotasi.coordinate
        awalPin.pinTintColor = .green
        awalPin.title = awalAnotasi.title

        let akhirPin = MyPointAnnotation()
        akhirPin.coordinate = akhirAnotasi.coordinate
        akhirPin.pinTintColor = .blue
        akhirPin.title = akhirAnotasi.title

        //titik marker
        self.mapRoute.showAnnotations([awalPin, akhirPin], animated: true)


        //menambahkan route
        let directionRequest = MKDirectionsRequest()
        directionRequest.source = awalMap
        directionRequest.destination = akhirMap
        directionRequest.transportType = .automobile

        let directions = MKDirections(request: directionRequest)
        directions.calculate
            {
                (response, error) -> Void in

                guard let response = response else
                {
                    if let error = error {
                        print("Error : \(error)")
                    }
                    return
                }

                let route = response.routes[0]


                self.mapRoute.add((route.polyline), level: MKOverlayLevel.aboveRoads)

                let rect = route.polyline.boundingMapRect
                self.mapRoute.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
                self.mapRoute.delegate = self

        }
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
     // MARK: - Navigation

     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
}

extension LocationViewController : MKMapViewDelegate
{
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let renderer = MKPolylineRenderer(overlay: overlay)
        renderer.lineWidth = 1.0
        renderer.strokeColor = UIColor.red

        return renderer
    }

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

        var annotView = mapView.dequeueReusableAnnotationView(withIdentifier: "myAnnotation") as? MKPinAnnotationView
        if annotView == nil {
            annotView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myAnnotation")
        }
        else {
            annotView?.annotation = annotation
        }
        if let annotation = annotation as? MyPointAnnotation {
            annotView?.pinTintColor = annotation.pinTintColor
            annotView?.canShowCallout = true
        }

        return annotView
    }

}

extension LocationViewController : CLLocationManagerDelegate
{
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        if let location = locations.last
        {
            if((location.horizontalAccuracy) < CLLocationAccuracy(0))
            {
                return
            }

            lokasiAwal2 = location

            self.updateUIAndGetDirection()
            self.corLoc.stopUpdatingLocation() //avoiding continue direction changes 
        }
    }

    func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {

        if status == CLAuthorizationStatus.authorizedWhenInUse || status == CLAuthorizationStatus.authorizedAlways {

            manager.startUpdatingLocation()

        }
    }
}