如何正确获取最顶层的视图控制器并投射它

时间:2015-02-16 10:12:53

标签: ios swift facebook-ios-sdk

嗨,我有这个导航堆栈:

NavigationController - > ViewController - >随后的VC

在最顶级的VC中,我有一个活动指示器,当用户点击“使用Facebook登录”然后想要在FBRequestConnection关闭时关闭时,我会打开它。 FBRequestConnection是异步的,因此需要在闭包内关闭它。

以下方法不是从LoginVC本身调用的,所以我需要将它从导航堆栈中取出。我试过了:

if let loginVC = UIApplication.sharedApplication().keyWindow?.rootViewController?.navigationController?.visibleViewController? as? LoginVC {
                    loginVC.turnOffActivityIndictator()
                }

还有:

if let loginVC = UIApplication.sharedApplication().delegate?.window??.rootViewController as? LoginVC {
                    loginVC.turnOffActivityIndictator()
                }

但它不起作用。我也尝试了其他建议,但无法找到解决方案。我如何解决这个问题,或者让其他人有更好的想法?

XCode中的变量窗口似乎看起来一切正常,但if let语句只是跳过尾随{},这意味着as?如果我是对的,会失败吗?

enter image description here

这是(不完整的)方法:

private class func makeRequestForUserData() -> Void {
    var dict = NSMutableDictionary()
    FBRequestConnection.startForMeWithCompletionHandler({(connection, result, error) -> Void in
        if (error == nil) {
            // Success! Include your code to handle the results here
            let resultDict = result as [String:AnyObject]
            if let usersEmail = resultDict["email"] as? String {
                if DBUser.loginUserForEmail(usersEmail) == true {
                    //Go to main menu
                }else {
                    // no user exists.. alert message
                    // take then to sign up page
                }
            }else{
                // error got nothing from the result dict!!
            }
            if let loginVC = UIApplication.sharedApplication().keyWindow?.rootViewController?.navigationController?.visibleViewController? as? LoginVC {
                loginVC.turnOffActivityIndictator()
            }
        } else {
            // An error occurred, we need to handle the error
            // Check out our error handling guide: https://developers.facebook.com/docs/ios/errors/
            FBErrorHandler.processError(error)
        }
    })
}

1 个答案:

答案 0 :(得分:1)

  

NavigationController - > ViewController - >随后的VC

从这个导航堆栈中你的rootViewController没有navigationController,但它本身就是navigationController 我认为UIApplication.sharedApplication().keyWindow?.rootViewController?.navigationController?正在回归。尝试将rootViewController转换为UINavigationController,然后获取它的viewControllers,然后获取所需的viewController

if let viewControllers = (UIApplication.sharedApplication().keyWindow?.rootViewController? as UINavigationController).viewControllers {

    //get first controller in hierarchy    
    if let loginVC = viewControllers[0] as? LoginVC{

        loginVC.turnOffActivityIndictator()
    }       
}