我有这个密码:

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        self.locationManager.requestWhenInUseAuthorization()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        super.viewDidLoad()
    }
    @IBAction func sendLocation() {
        locationManager.startUpdatingLocation()
    }
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let coordinate = locations.last?.coordinate else { return }
        print(String(coordinate.latitude))
        locationManager.stopUpdatingLocation()
    }
}

当点击UIButton时,IBAction被调用,当前用户位置显示在控制台中。
因为我只需要获取一次位置,所以我想使用locationManager.requestLocation()
但是当删除locationManager.stopUpdatingLocation()并将locationManager.startUpdatingLocation()替换为locationManager.requestLocation()时,当在控制台中按UIButton并使用以下日志时,应用程序将崩溃:
2019-01-09 15:48:36.585518+0100 GetLocation[1206:248754]***断言
失败-[CLLocationManager requestLocation],
/BuildRoot/Library/Caches/com.apple.xbs/Sources/CoreLocation Framework/CoreLocation-2245.8.25/Framework/CoreLocation/CLLocationManager.m:897
2019-01-09 15:48:36.586443+0100获取位置[1206:248754]***
由于意外异常而终止应用程序
'nsInternalConsistencyException',reason:'委托必须响应
位置经理:didFailWithError:'
***第一个抛出调用堆栈:
(0x1b4e08ec4 0x1b3fd9a50 0x1b4d1eb3c 0x1b580d1d0 0x1bbcd8280)
0x104690028 0x10469005c 0x1e20f23f8 0x1e1b7ffb8 0x1e1b802d8
0x1e1b7f2d8 0x1e212bb50 0x1e212cdb4 0x1e210c0b0 0x1e21daf1c
0x1e21dd914 0x1e21d6404 0x1b4d991f0 0x1b4d99170 0x1b4d98a54
0x1b4d93920 0x1b4d931f0 0x1b700c584 0x1e20f0ce4 0x104691564
0x1b4852bb4号)
libc++abi.dylib:以类型为的意外异常终止
非例外
(内陆开发银行)
为什么?我做错什么了?

最佳答案

你可能需要实施

func locationManager(_ manager: CLLocationManager,
         didFailWithError error: Error) {  --- }

CLLocationManagerDelegate的委托方法

10-08 05:23