swift - 如果我使用 TabBar 导航,如何从 AppDelegate 调用 viewcontroller 方法

标签 swift uitabbarcontroller appdelegate

当远程通知进入时,我的应用程序一打开,尤其是在使用 TabBar 导航时,我真的需要帮助调用 View Controller 方法。当我在通知到达时打开我的应用程序时,它将调用 didReceiveRemoteNotification 因为我启用了“content-available = 1”。但是,问题是我不知道如何访问我的 HomeViewController 方法 refresh() 因为我使用 TabBar导航。我需要在 didReceiveRemoteNotification 中调用 HomeViewController refresh() 方法,因为它确实需要从核心刷新数据,到达的通知是保存在核心数据。

每次收到通知时,我都会将它们保存在领域数据库中并在 HomeViewController 中显示给用户

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
    if let aps = userInfo["aps"] as? NSDictionary{
        if let alert = aps["alert"] as? NSDictionary{
            if let mbody = alert["body"] as? String{
                print("Message Body : \(body)")
                body = mbody
            }
            if let mtitle = alert["title"] as? String{
                print("Message Title : \(title)")
                title = mtitle
            }
        }
    }

    let newNotification = NotificationList()
    newNotification.title = title
    newNotification.body = body
    //Realm insert query
    oneSignalHelper.insertOneSignalNotification(newNotification)

    print("Remote Receive")
    //This condition isn't working
    if let viewController = self.window?.rootViewController as? HomeViewController {
        print("Remote Receive Read")
        //This method is HomeViewController method which I gonna use for refresh when I tapped notification.It read that are save in realm database and show results.
        viewController.readNotificationsAndUpdateUI()
    }

    handler(UIBackgroundFetchResult.NewData)

}

这是 HomeViewControllerreadNotificationsAndUpdateUI()

func readNotificationsAndUpdateUI(){
    notifications = realm.objects(NotificationList)
    self.notificationTableView.setEditing(false, animated: true)
    self.notificationTableView.reloadData()
    self.refreshControl?.endRefreshing()
}

最佳答案

我建议你使用 NSNotificationCenter,只需在 didReceiveRemoteNotification 中发布通知,如下所示:

NSNotificationCenter.defaultCenter().postNotificationName("refreshNotification", object: nil)

viewDidLoad() 的 HomeViewController 中,您应该像这样订阅通知中心:

NSNotificationCenter.defaultCenter().addObserver( self, selector: "refresh", name: "refreshNotification", object: nil)

关于swift - 如果我使用 TabBar 导航,如何从 AppDelegate 调用 viewcontroller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34281938/

相关文章:

ios - 在推送通知 Swift 2 AppDelegate 上加载特定的 viewController

ios - AppDelegate Swift 中的选项卡式应用程序和核心数据功能

ios - 以方形格式保存照片

ios - 如何在我的应用程序中保存图像(路径)?

macos - 访问 swift 数组时在运行时出现 EXC_BAD_ACCESS

iOS swift 标签栏的奇怪行为

swift - 按钮,如何在导航栏中嵌入的swiftUI中打开新 View

Swift Tabbar Controller 栏按钮项目

ios - 是否可以删除 UITabBarItem 中的图像并垂直对齐标题

ios - 快速入口点