首页 > 解决方案 > 如何以编程方式将 VC 放置在导航控制器中?

问题描述

每当我尝试展示此 VC 时,我目前都会遇到错误。错误是Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value我相信这是因为 VC 不在导航控制器中。如何将此 VC 放入导航控制器(以编程方式)。

import UIKit
import AWSAuthCore
import AWSAuthUI
import AWSMobileClient

class SignInViewController: UIViewController {



    override func viewDidLoad() {
        super.viewDidLoad()
        AWSMobileClient.default()
        .showSignIn(navigationController: self.navigationController!, // this is where i get the error.
                         signInUIOptions: SignInUIOptions(
                               canCancel: true,
                               logoImage: UIImage(named: "MyCustomLogo"),
                                backgroundColor: UIColor.red)) { (result, err) in

        AWSMobileClient.default().initialize { (userState, error) in
                   if let userState = userState {
                       switch(userState){
                       case .signedIn:

                               DispatchQueue.main.async {


                           }
                       case .signedOut:
                           AWSMobileClient.default().showSignIn(navigationController: self.navigationController!, { (userState, error) in
                                   if(error == nil){       //Successful signin
                                       DispatchQueue.main.async {


                                       }
                                   }
                               })
                       default:
                           AWSMobileClient.default().signOut()

                       }

                   } else if let error = error {
                       print(error.localizedDescription)
                   }
               }

    }



    }




}

这是来自的代码AppDelegate

import UIKit
import AWSAppSync
import AWSMobileClient


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var appSyncClient: AWSAppSyncClient?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        let nav1 = UINavigationController()
        let mainView = SignInViewController(nibName: nil, bundle: nil)
        nav1.viewControllers = [mainView]
        self.window!.rootViewController = nav1
        // Override point for customization after application launch.
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = UINavigationController(rootViewController: TabBarController())
        window?.makeKeyAndVisible()
        AWSMobileClient.default().addUserStateListener(self) { (userState, info) in
                      switch (userState) {
                      case .guest:
                          print("user is in guest mode.")
                      case .signedOut:
                        self.window?.rootViewController?.present(SignInViewController(), animated: true, completion: nil)
                          print("user signed out.")
                      case .signedIn:
                          print("user is signed in.")
                      case .signedOutUserPoolsTokenInvalid:
                          print("need to login again.")
                      case .signedOutFederatedTokensInvalid:
                          print("user logged in via federation, but currently needs new tokens")
                      default:
                          print("unsupported")
                      }
                  }


        AWSMobileClient.default().initialize { (userState, error) in
                 if let userState = userState {
                     print("UserState: \(userState.rawValue)")
                 } else if let error = error {
                     print("error: \(error.localizedDescription)")
                 }
             }
        do {
            // You can choose the directory in which AppSync stores its persistent cache databases
            let cacheConfiguration = try AWSAppSyncCacheConfiguration()

            // AppSync configuration & client initialization
            let appSyncServiceConfig = try AWSAppSyncServiceConfig()
            let appSyncConfig = try AWSAppSyncClientConfiguration(appSyncServiceConfig: appSyncServiceConfig,
                                                                  cacheConfiguration: cacheConfiguration)
            appSyncClient = try AWSAppSyncClient(appSyncConfig: appSyncConfig)
            print("Initialized appsync client.")
        } catch {
            print("Error initializing appsync client. \(error)")
        }

        return true
    }

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }


}

标签: swift

解决方案


嵌入SignInViewController在一个UINavigationController.

为此,将 a 拖放UINavigationController到 theStoryboardCTRL + drag从 that拖放UINavigationControllerSignInViewController,选择关系rootViewController

以编程方式:

var nav1 = UINavigationController()
var mainView = SignInViewController(nibName: nil, bundle: nil) 
nav1.viewControllers = [mainView]
self.window!.rootViewController = nav1

推荐阅读