Swift 检测何时从 UIApplication.shared.open 返回

标签 swift url maps

最初我想在我的应用程序中显示谷歌地图方向,但我认为这是不可能的。所以我要做的是让我的应用程序在需要时打开 Google map 应用程序。

我可以很好地打开 Google map ,但是我希望在他们到达目的地后让我的应用转到另一个屏幕。

有什么方法可以检测到吗?如果不是,那么在用户返回到我的应用程序后转至另一个 View Controller 的最佳方式是什么?

这是我的代码:

  override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
    if let cell = tableView.cellForRow(at: indexPath) as? LocationCell {
        if(indexPath.row == 0){
            cell.selectionStyle = .none
            browseVillages(cell.villageBtn)
        }

        else{
            cell.selectionStyle = .none

            let googleMaps = URL(string: "comgooglemaps-x-callback://")!
            if UIApplication.shared.canOpenURL(googleMaps) {
                let directionsRequest = "comgooglemaps-x-callback://" +
                    "?daddr=\(bars[indexPath.row]["Latitude"]!),\(bars[indexPath.row]["Longitude"]!)&saddr=\(currentLocation!.coordinate.latitude),\(currentLocation!.coordinate.longitude)" +
                "&x-success=MYAPP://?resume=true&x-source=AirApp"

                let directionsURL = URL(string: directionsRequest)!
                UIApplication.shared.open(directionsURL, options: [:], completionHandler: nil)
            }
            else {
                let alert = UIAlertController(title: "Error", message: "MYAPP uses Google Maps to display accurate directions to \(bars[indexPath.row]["Name"]).", preferredStyle: UIAlertControllerStyle.alert)
                alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
                self.present(alert, animated: true, completion: {  })
            }
        }
    }
}

最佳答案

在某些地方如application(_:didFinishLaunchingWithOptions:) 将“comeFromMaps”UserDefaults 注册为 false,然后将它放在打开 map 链接之前:

UserDefaults.standard.set(true, forKey: "comeFromMaps")

然后将它放在 AppDelegateapplication Did Become Active(_: ) 中:

let comeFromMaps = UserDefaults.standard.bool(forKey: "comeFromMaps")
if comeFromMaps {
    UserDefaults.standard.set(false, forKey: "comeFromMaps")
    // perform the segue!
}

此外,您可以使用 MapKit 获取方向,使用 MKDirections class .

关于Swift 检测何时从 UIApplication.shared.open 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42943446/

相关文章:

ios - Swift 3 使用 NSAttributedString 渲染 textview 但想要更改默认字体

ios - 单击 SwiftUI 中的 NavigationLink 后隐藏 TabView

c# - GetPathByAction 为 Dictionary<string,string> 创建错误的查询参数

delphi - Delphi 2009 应用程序中的 Google map

ios - 如何将 ios esri arcGIS 点转换为纬度和经度

swift - 不要给我五个挑战—— swift

ios - 如何共享 View Controller 的 View 布局

带 URL 参数的 Java 启动

JAVASCRIPT:如何获取页面中链接的 URL?

css - map 自动完成未以模态 Angular 显示。 z-index 不工作