首页 > 解决方案 > 在 Swift 4 中加载应用程序时崩溃?

问题描述

当应用程序加载时出现此错误时我遇到了崩溃:Failed to instantiate the default view controller for UIMainStoryboardFile 'Main' - perhaps the designated entry point is not set?所以,Main.Storyboard我不检查is initial view controller,因为正如您在我的代码中看到的那样,我正在AppDelegate我的assertionFailure(). 谁能帮我解决这个问题?谢谢您的帮助。另外,我输入LocationViewController了未选中的 Storyboard ID Use storyboard id。(我什至检查过它仍然是同样的错误)。

这是我的代码:

class AppDelegate: UIResponder, UIApplicationDelegate {
    let window = UIWindow()
    let locationService = LocationService()
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let service = MoyaProvider<YelpService.BusinessesProvider>()
    let jsonDecoder = JSONDecoder()

       func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
    service.request(.search(lat: 34.148000, long: -118.361443)) { (result) in
        switch result {
        case .success(let response):
            let root = try? self.jsonDecoder.decode(Root.self, from: response.data)
            print(root)
        case .failure(let error):
            print("Error: \(error)")
        }
    }

    let locationViewController = storyboard.instantiateViewController(withIdentifier: "LocationViewController") as? LocationViewController
    locationViewController?.locationService = locationService
    window.rootViewController = locationViewController

    window.makeKeyAndVisible()

    return true
}
}

标签: iosswift

解决方案


您的应用程序正在崩溃,因为您的 locationService.status 处于默认状态,因此它总是达到 assertionFailure()。

当控制流预计不会到达调用时,使用此函数停止程序,而不影响交付代码的性能 - 例如,在您知道必须满足其他情况之一的 switch 的默认情况下 https://developer.apple.com/documentation/swift/1539616-assertionfailure

1)找到一种方法来修复你的 locationService.status

2)绕过switch语句

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
    service.request(.search(lat: 34.148000, long: -118.361443)) { (result) in
        switch result {
        case .success(let response):
            let root = try? self.jsonDecoder.decode(Root.self, from: response.data)
            print(root) <-- Console is printing nil here because your jsonDecoder failed.
        case .failure(let error):
            print("Error: \(error)")
        }
    }

    let locationViewController = storyboard.instantiateViewController(withIdentifier: "LocationViewController") as? LocationViewController
    locationViewController?.locationService = locationService
    window.rootViewController = locationViewController

    window.makeKeyAndVisible()

    return true
}

推荐阅读