首页 > 解决方案 > 调用 requestLocation() 时的“线程 1:信号 Sigabrt”

问题描述

尝试使用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()
    }
}

我希望有人能告诉我我做错了什么,或者我应该用 startUpdatingLocation() 替换 requestLocation()。

标签: swift

解决方案


Apple 在文档中声明,如果您希望使用,您必须实现这些委托方法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)")
    }

}

推荐阅读