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

标签 ios swift

我正在尝试使用 Google map 获取从用户当前位置到目的地的路线。我希望在按下 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()
    }
}

非常感谢任何帮助!

最佳答案

如果你想在另一个函数中使用它,你需要在类中创建一个内部变量来存储位置。例如

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

didUpdateLocations 中:

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

现在您可以在 func showDirection() 中访问它

关于ios - Swift - 从类扩展中的 locationManager 函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35261201/

相关文章:

ios - 苹果如何切换到客户端的开发者控制台

android - Web 应用程序可以控制 native 操作系统控件吗?

iphone - 将 NSString 传递给 Webview

ios - 如何在 iOS 开发中最小化带有大量图像的应用程序大小?

ios - 使用 SwiftyJSON 包

iOS UILabel 自动调整文本大小以适应框架,无论字体如何

ios - 我们应该使 tapGesture 组件成为 IBAction 还是 IBOutlet 来捕获点击事件?

ios - 解除 UISearchBar 键盘后取消按钮消失

ios - 使用新的 iOS 11 API 重新排序 tableview 时动画不正确

ios - Swift:如何将闭包参数从类方法传递给类中的函数