最初我想在我的应用程序中显示谷歌地图方向,但我认为这是不可能的。所以我要做的是让我的应用程序在需要时打开 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")
然后将它放在 AppDelegate
的 application 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/