Moovit 集成导致崩溃

Moovit Integration Causes Crash

我正在尝试将 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 中,所以我不知道是什么导致了崩溃...我错过了什么吗?

如果有人能帮我解决这个问题,我将不胜感激,谢谢。

将 urlString 转换为 URL 将返回 nil,并且您正在强制展开 nil。因此它崩溃了。

您应该在展开前检查 nil

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>"
       if let url = URL(string: MoovitURL) {
            UIApplication.shared.openURL(url)
       }
}

并且不要忘记在您的 url 中添加您的合作伙伴 ID。

它会起作用,

由于您的字符串 Times Square 中的 space,无法创建 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)!)
    }