调用requestLocation()时出现“线程1:信号Sigabrt”

时间:2019-05-14 04:50:54

标签: swift

尝试使用CLlocationManager().requestLocation()获取用户的当前位置。但是该应用程序崩溃并显示信号Sigabrt。我知道这可能是因为插座未连接,所以我确保它们都已连接,但编译器仍会弹出此警告。我已经正确实施了 顺便说一句p.list中的键。

有趣的是,当我将requestLocation()更改为startUpdatingLocation()时,一切正常。

let locationManager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()

    locationManager.requestAlwaysAuthorization()
    locationManager.requestWhenInUseAuthorization()
    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestLocation()
    }
}

我希望有人能告诉我我做错了什么,还是我应该将requestLocation()替换为startUpdatingLocation()。

1 个答案:

答案 0 :(得分:0)

Apple在documentation中声明,如果您想使用requestLocation(),则必须实现这些委托方法:

locationManager(_:didUpdateLocations:)locationManager(_:didFailWithError:)

下面的代码对我有用。

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.requestAlwaysAuthorization()
        locationManager.requestWhenInUseAuthorization()
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestLocation()
        }

    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print("LOCATIONS: \(locations)")
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("ERROR: \(error)")
    }

}