Swift - 在类扩展中从locationManager函数返回值

时间:2016-02-08 01:16:16

标签: ios swift

我正在尝试使用Google地图从用户当前位置获取路线到目的地。我希望在按下showDirection按钮时完成此操作,但我无法想象如何从func locationManager(... didUpdateLocation)返回或将用户位置传递到IBAction函数,因为IBAction不使用其中的参数我可以将locValue传递给。

这是showDirection按钮功能:

@IBAction func showDirection(sender: AnyObject) {
    print("Running showDirection")
    let instanceOne = ParseViewController() // Create ParseViewController instance to operate on
    print("Created ParseView instance")
    let Coord = instanceOne.returnParse()
    let latitude = (Coord.lat as NSString)
    let longitude = (Coord.long as NSString)
    var urlString = "http://maps.google.com/maps?"
    urlString += "saddr= // Users location from didUpdateLocation"
    urlString += "&daddr= \(latitude as String), \(longitude as String)"
    print(urlString)

    if let url = NSURL(string: urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
    {
        UIApplication.sharedApplication().openURL(url)
    }
}

这是带有locValue的locationManager函数:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.first {
        mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
        let locValue:CLLocationCoordinate2D = (manager.location?.coordinate)!
        print("Coordinates = \(locValue.latitude), \(locValue.longitude)")
        locationManager.stopUpdatingLocation()
    }
}

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

如果要在另一个函数中使用它,则需要在类中创建一个内部变量来存储该位置。 E.g。

class YourViewController: UIViewController ... {
    var lastLocation: CLLocation? = nil
    ...
}

didUpdateLocations

if let location = locations.first {
    lastLocation = location
    ...
}

现在您可以在func showDirection()

中访问它了