我正在尝试将Moovit实施到我的应用中,以便用户可以轻松获取到某个地方的公交路线。
但是我遇到了一些困难...
更新的代码:

func openMoovit(To : CLLocationCoordinate2D) {
    if UIApplication.shared.canOpenURL(URL(string: "moovit://")!) {
        // Moovit installed - launch app (with parameters)
        let MoovitURL: String = "moovit://directions?dest_lat=\(To.latitude)&dest_lon=\(To.longitude)&dest_name=\(barNameTemplate))&auto_run=true&partner_id=<TestApp>"
        let escapedString = MoovitURL.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
        UIApplication.shared.openURL(URL(string: escapedString!)!)
        }else {
// Moovit not installed - send to store
UIApplication.shared.openURL(URL(string: "https://itunes.apple.com/us/app/id498477945")!)
这是Moovit iOS API的基础
然后当我按下按钮时简单地调用该函数:
let MoovitButton = UIAlertAction(title: "Moovit", style: .default) { action -> Void in

self.openMoovit(To : self.CoordinatesTemplate)// calling function
print("Moovit Chosen!")
该代码在Waze集成中运行良好,但在Moovit中运行失败...
当我按下按钮时,它在行崩溃:
UIApplication.shared.openURL(URL(string: MoovitURL)!)
说:
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
我也将moovit添加到了我的Plist中,所以我不知道是什么原因导致了崩溃...我错过了什么吗?
如果有人可以帮助我解决这个问题,我将不胜感激,谢谢。

最佳答案

会工作的,

由于字符串Times Square中存在空格,因此无法创建URL对象:

func openMoovit(To : CLLocationCoordinate2D) {
    if UIApplication.shared.canOpenURL(URL(string: "moovit://")!) {
         // Moovit installed - launch app (with parameters)
         let MoovitURL: String = "moovit://directions?dest_lat=40.758896&dest_lon=-73.985130&dest_name=Times Square&orig_lat=40.735845&orig_lon=-73.990512&orig_name=Union Square&auto_run=true&partner_id=<TestApp>"
         var escapedString = MoovitURL.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
         UIApplication.shared.openURL(URL(string: escapedString)!)
    }

10-05 20:03