簡體   English   中英

如何在macOS、swift中獲取位置坐標

[英]How to get location coordinates in macOS、swift

我需要在 Mac OS 上獲取地理坐標。 這是我的代碼,但是運行時報錯: domain = kclerrordomain code = 0 "(null)"

import Cocoa
import CoreLocation

    let locationManager:CLLocationManager = CLLocationManager()
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        //設置定位服務管理器代理
        locationManager.delegate = self
        //設置定位進度
        locationManager.desiredAccuracy = kCLLocationAccuracyBest //最佳定位
        //更新距離
//        locationManager.distanceFilter = 100
        //發出授權請求
        locationManager.requestAlwaysAuthorization()

        if (CLLocationManager.locationServicesEnabled()){
            //允許使用定位服務的話,開始定位服務更新

//            print("定位開始")

        }
    }

extension ViewController:CLLocationManagerDelegate{
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        //獲取最新的坐標
        let currLocation : CLLocation = locations.last!  // 持續更新
        print("緯度:\(currLocation.coordinate.latitude) 緯度:\(currLocation.coordinate.longitude) 海拔:\(currLocation.altitude) 水平精度:\(currLocation.horizontalAccuracy) 垂直精度:\(currLocation.verticalAccuracy) 方向:\(currLocation.course) 速度:\(currLocation.speed)")
    }
    func locationManager(_ manager: CLLocationManager,
                        didChangeAuthorization status: CLAuthorizationStatus) {
        print("location manager auth status changed to:" )
        switch status {
            case .restricted:
                print("status restricted")
            case .denied:
                print("status denied")

            case .authorized:
                print("已授權")
                locationManager.startUpdatingLocation()
            case .notDetermined:
                print("status not yet determined")

            default:
                print("unknown state: \(status)")
        }
    }

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

在此處輸入圖片說明

運行應用程序時:在此處輸入圖像描述

您需要在info.plist文件中添加位置使用說明。 添加您的 info.plist 后應如下所示<code>info.plist</code> .

viewDidLoad添加這一行。

manager.startUpdatingLocation()

然后添加更新位置的委托方法。

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    print(locations.last?.coordinate)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM