是否可以从locationManager函数返回双精度数?

时间:2018-12-23 20:48:36

标签: ios cllocation

我希望能够在每个IBAction函数内调用locationManager函数。但是我不知道如何在函数调用中处理所有locationManager参数。我该如何处理函数调用中的所有参数?

我试图做这样的事情。

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) -> Double {
    ...
    return distance
    }

但是我收到警告,指出它的格式不正确。然后,我不知道该怎么称呼locationManager。

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    let latWork = 39.950230
    let longWork  = -75.158820
    let latHome = 40.005140
    let longHome = -75.210040

    let locationManager = CLLocationManager()

    @IBOutlet weak var distanceTraveledLabel: UILabel!

    @IBOutlet weak var distanceRemainingLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.requestWhenInUseAuthorization()

        locationManager.delegate = self
        locationManager.desiredAccuracy = 
kCLLocationAccuracyHundredMeters
        locationManager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, 
didUpdateLocations locations: [CLLocation]) {
        let location = locations.last!
        let distance = location.distance(from: CLLocation(latitude: 
CLLocationDegrees(latWork), longitude: CLLocationDegrees(longWork)))
        print(distance)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func homeTapped(_ sender: Any) {
        //function that happens when home button is tapped
        print("you tapped home")
        //call locationManager function
    }

@IBAction func workTapped(_ sender: Any) {
        //function that happens when work button is tapped
        print("you tapped work")
        //call locationManager function
    }
}

1 个答案:

答案 0 :(得分:0)

您可以做的是;有两个变量可以将纬度和经度保持为两倍(或者您也可以将一个变量作为位置):

var latitude: Double?
var longitude: Double?

然后,每次使用didUpdateLocations方法更改位置时,更新这些变量:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.last {
        latitude = location.coordinate.latitude
        longitude = location.coordinate.longitude
    }
}

然后在您的操作方法中,从那些较长的值中获取位置信息,例如:

//you can access the current location from lat long values, and then calculate distances inside action buttons if you like.
@IBAction func homeTapped(_ sender: Any) {
    //latitude, longitude will be updated with user's current location.

}

@IBAction func workTapped(_ sender: Any) {
    //latitude, longitude will be updated with user's current location.       
}