在 swift3 中从 AppDelegate 调用函数
Calling Functions From AppDelegate in swift3
我正在使用 OneSignal
在我的应用程序中处理通知。这是在 AppDelegate.swift
中启动的,其中有一个处理接收到的应用程序的函数:
let notificationReceivedBlock: OSHandleNotificationReceivedBlock = { notification in
print("Received Notification: \(notification!.payload.body)")
}
然后我有一个带有 5 个选项卡的 TabViewController
,每个选项卡的 navigationItem 都有一个 UINavigationBarButton
,可以将您发送到消息视图。每当有通知显示用户收到新消息时,我想更改该按钮中的徽章编号。我在每个 viewController(5 个选项卡中的每一个)中都有一个函数会更新它。
问题是 AppDelegate
需要调用这个函数 updateBadgeNumber
而我不知道该怎么做。另外,一些选项卡甚至可能还没有初始化。有谁知道如何从 AppDelegate
?
调用 ViewControllers 中的函数
谢谢。
编辑:
感谢下面的@paulvs 找到了解决方案。他将我链接到我发现这个的答案:Find Top View Controller in Swift
答案取决于您的 UITabBarController
是否是您应用的根视图控制器。
- 如果您的
UITabBarController
是根视图控制器,您可能在应用程序委托中引用了它,并且可以使用 UITabBarController
的 selectedViewController
属性 来获取当前视图控制器,然后设置徽章值。 (如果您没有参考,您可以将 window.rootViewController
转换为 UITabBarController
来访问它。)
- 如果不是,您可以使用代码 like this 找到当前可见的视图控制器。 (然后要访问
UITabBarController
,您可以将 parentViewController
转换为 UITabBarController
,然后从那里访问其他视图控制器并设置它们的标记值。)
我正在使用 OneSignal
在我的应用程序中处理通知。这是在 AppDelegate.swift
中启动的,其中有一个处理接收到的应用程序的函数:
let notificationReceivedBlock: OSHandleNotificationReceivedBlock = { notification in
print("Received Notification: \(notification!.payload.body)")
}
然后我有一个带有 5 个选项卡的 TabViewController
,每个选项卡的 navigationItem 都有一个 UINavigationBarButton
,可以将您发送到消息视图。每当有通知显示用户收到新消息时,我想更改该按钮中的徽章编号。我在每个 viewController(5 个选项卡中的每一个)中都有一个函数会更新它。
问题是 AppDelegate
需要调用这个函数 updateBadgeNumber
而我不知道该怎么做。另外,一些选项卡甚至可能还没有初始化。有谁知道如何从 AppDelegate
?
谢谢。
编辑:
感谢下面的@paulvs 找到了解决方案。他将我链接到我发现这个的答案:Find Top View Controller in Swift
答案取决于您的 UITabBarController
是否是您应用的根视图控制器。
- 如果您的
UITabBarController
是根视图控制器,您可能在应用程序委托中引用了它,并且可以使用UITabBarController
的selectedViewController
属性 来获取当前视图控制器,然后设置徽章值。 (如果您没有参考,您可以将window.rootViewController
转换为UITabBarController
来访问它。) - 如果不是,您可以使用代码 like this 找到当前可见的视图控制器。 (然后要访问
UITabBarController
,您可以将parentViewController
转换为UITabBarController
,然后从那里访问其他视图控制器并设置它们的标记值。)