Swift:获取当前用户坐标并将其存储到变量中

Swift: Get Current User Coordinates and Store them into a Variable

我目前正在尝试获取用户的当前坐标,并最终将这些值存储到变量中。

我创建了以下 class 来定义用户当前位置并设置提取数据的函数。

import Foundation
import CoreLocation

class MyCurrentCoordinate: NSObject {


     private var currentLocation: CLLocation!

     var myLatitude = 0.0
     var myLongitude = 0.0
     var myAltitude = 0.0

     override init() {
         super.init()
     }

     func getLat() {
         myLatitude = currentLocation.coordinate.latitude
     }

     func getLong() {
         myLongitude = currentLocation.coordinate.longitude
     }

     func getAlt() {
         myAltitude = currentLocation.altitude
     }
}

这没有显示任何错误。但是,当我去调用任何函数(getLat、getLong 或 getAlt)来提取一段用户位置数据时,由于值为 nil,应用程序崩溃了。有没有人知道为什么没有传递实际用户纬度、经度或海拔高度?

我有位置权限,info.plist更新为允许用户授予位置跟踪权限。

你可以使用 CLLocationManager

  1. 添加应用能力,您可以打开您的info.plist喜欢的源代码并添加:

    <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
    <string>App requires allways tracking</string>
    <key>NSLocationAlwaysUsageDescription</key>
    <string>App requires background tracking</string>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>App requires tracking when be in use</string>
    
    <key>UIBackgroundModes</key>
    <array>
        <string>fetch</string>
        <string>location</string>
        <string>remote-notification</string>
    </array>
    
  2. 请求像 locationManager.requestAlwaysAuthorization() 这样的授权并管理是否有正确的访问权限... CLLocationManager.authorizationStatus() == .authorizedAlways

    import CoreLocation
    
    class ViewController: UIViewController, CLLocationManagerDelegate {
        var locationManager: CLLocationManager?
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            locationManager = CLLocationManager()
            locationManager?.delegate = self
            locationManager?.requestAlwaysAuthorization()
            if CLLocationManager.authorizationStatus() == .authorizedAlways {
                locationManager.allowsBackgroundLocationUpdates = true
                locationManager.pausesLocationUpdatesAutomatically = false
                locationManager.desiredAccuracy = kCLLocationAccuracyBest
                locationManager.startUpdatingLocation()
            }
            if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
                locationManager.allowsBackgroundLocationUpdates = false
                locationManager.pausesLocationUpdatesAutomatically = true
                locationManager.desiredAccuracy = kCLLocationAccuracyBest
                locationManager.startUpdatingLocation()
            }
        }
    }
    
    extension ViewController: CLLocationManagerDelegate {
    
        public func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]){
            guard let location = locations.first else { return }
            print(location)
    
        }
    
        public func locationManager(_: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
            switch status {
            case .notDetermined:
                print("Autorization status did change \(status)")
            case .authorizedWhenInUse:
                print("Autorization status did change \(status)")
            case .authorizedAlways:
                print("Autorization status did change \(status)")
            case .restricted:
                print("Autorization status did change \(status)")
            case .denied:
                print("Autorization status did change \(status)")
            @unknown default:
                fatalError()
            }
        }
    }
    
  3. 不要忘记在某个地方停止locationManager.stopUpdatingLocation()

import Foundation
import CoreLocation
import UIKit

public protocol LocalizationHelperDelegate: class {
    func didUpdateLocation(_ sender: CLLocation)
}

public class LocalizationHelper: NSObject {

    public weak var delegate: LocalizationHelperDelegate?
    public static var shared = LocalizationHelper()

    private lazy var locationManager: CLLocationManager = {
        let locationManager = CLLocationManager()
        locationManager.requestAlwaysAuthorization()
        locationManager.allowsBackgroundLocationUpdates = true
        locationManager.pausesLocationUpdatesAutomatically = false
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        return locationManager
    }()

    private var currentLocation: CLLocationCoordinate2D?

    public func startUpdatingLocation() {
        locationManager.delegate = self
        locationManager.startUpdatingLocation()
    }

    public func stopUpdatingLocation() {
        locationManager.stopUpdatingLocation()
    }

    public func getCurrentLocation() -> CLLocationCoordinate2D? {
        return currentLocation
    }

    public func getLat() -> Double{
        return currentLocation?.latitude ?? 0.0
    }

    public func getLon() -> Double{
        return currentLocation?.longitude ?? 0.0
    }


}

extension LocalizationHelper: CLLocationManagerDelegate {

    public func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]){
        guard let location = locations.first else { return }
        currentLocation = location.coordinate
        print("[Update location at - \(Date())] with - lat: \(currentLocation!.latitude), lng: \(currentLocation!.longitude)")
        delegate?.didUpdateLocation(location)
    }
}

如何使用

LocalizationHelper.shared.Start()
...
let lat = LocalizationHelper.shared.getLat()
let lon = LocalizationHelper.shared.getLon()
...
LocalizationHelper.shared.Stop()