0

如果有人向我发送消息并且我在特定的视图控制器 (ConversationViewController) 中,我会尝试显示通知。现在,我可以显示通知,但是当我尝试访问 ConversationViewController 中的变量 (otherProfileName) 时,它是 nil。我猜这是因为该变量(otherProfileName)是从另一个视图控制器传递的。我确信该变量已成功传递。一切正常,可以显示通知并打印“hi”,但变量为零。有什么建议可以解决吗?

对话视图控制器

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

应用委托

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
}
4

2 回答 2

0

这段代码没有意义:

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

翻译:

“如果顶部视图控制器是 ConversationViewController,则创建一个新的 ConversationViewController 空实例,并询问该实例的 otherProfileName 值”

这就像在一组盒子中寻找蓝色盒子,因为您知道它包含一个苹果。当你找到一个蓝色盒子时,去建造一个新的空蓝色盒子,打开它,想知道为什么里面没有你的苹果。

于 2016-04-30T00:58:54.237 回答
0

您正在此处创建 ConversationViewController 的新实例

let myCustomViewController: ConversationViewController = ConversationViewController(nibName: nil, bundle: nil)

尝试

      if let myCustomViewController = topViewController() as? ConversationViewController {
            print(myCustomViewController.otherProfileName)
            print("HI")
            HDNotificationView.showNotificationViewWithImage(nil, title: "HI", message: "HHIHI", isAutoHide: true)
        }
     }
于 2016-04-30T01:00:15.243 回答