Tony Tony - 7 months ago 83
Swift Question

Access a variable from another view controller. Swift

I am trying to present a notification if someone send me a message and I am in a specific view controller (ConversationViewController). Right now, I can present the notification, but when I try to access a variable (otherProfileName) in ConversationViewController, it is nil. I guess it is because that variable (otherProfileName) is passed from another view controller. I am sure that the variable is passed successfully. Everything works well as notification can be showed and "hi" is printed, but the variable is nil. Any suggestion to fix it?

ConversationViewController

// passed from another view controller
var otherProfileName = String()


appDelegate

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
if application.applicationState == UIApplicationState.Active {
print(topViewController())
if topViewController() is ConversationViewController {
let myCustomViewController: ConversationViewController = ConversationViewController(nibName: nil, bundle: nil)
print(myCustomViewController.otherProfileName)
print("HI")
HDNotificationView.showNotificationViewWithImage(nil, title: "HI", message: "HHIHI", isAutoHide: true)
}
}
completionHandler(UIBackgroundFetchResult.NewData)
}

func topViewController(base: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? {
if let MMDrawers = base as? MMDrawerController {
for MMDrawer in MMDrawers.childViewControllers {
return topViewController(MMDrawer)
}
}
if let nav = base as? UINavigationController {
return topViewController(nav.visibleViewController)
}
if let tab = base as? UITabBarController {
if let selected = tab.selectedViewController {
return topViewController(selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(presented)
}
return base
}

Answer

This code makes no sense:

    if topViewController() is ConversationViewController {
        let myCustomViewController: ConversationViewController = ConversationViewController(nibName: nil, bundle: nil)

Translation:

"If the top view controller is a ConversationViewController, create a new, empty instance of ConversationViewController, and ask that instance for it's otherProfileName value"

It's like looking through a set of boxes for the blue box, since you know it contains an apple. When you find a blue box, go build a new, empty blue box, open it, and wonder why it doesn't contain your apple.