I'm sending a push notification from Amazon SNS to an ios app in swift ver. 3. When the push notification arrives the app switches to the second tab bar item on my device as per this SO thread. MyGlobalVariables is a struct updated in AppDelegate.swift and read in the viewcontroller.
AppDelegate.swift
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
if let aps = userInfo["aps"] as? NSDictionary {
if let alert = aps["alert"] as? NSDictionary {
if let title = alert["title"] as? String {
MyGlobalVariables.pushTitle = title
}
if let body = alert["body"] as? String {
MyGlobalVariables.pushBody = body
}
}
}
if self.window!.rootViewController as? UITabBarController != nil {
let tabbarController = self.window!.rootViewController as! UITabBarController
tabbarController.selectedIndex = 1
}
}
In SecondViewController.swift the text is update in viewWillAppear() and all is fine.
override func viewWillAppear(_ animated: Bool) {
pushTitleLabel?.text = MyGlobalVariables.pushTitle
}
If a new push notification with a different title is sent while I am in this tab I'd like the text label to be updated without navigating away and back.
I have tried to refresh the text label by adding this to AppDelegate.swift.
let sVC = SecondViewController()
if let title = alert["title"] as? String {
MyGlobalVariables.pushTitle = title
sVC.updateLabel(t: title)
}
And have this function in SecondViewController.swift
func updateLabel(t: String) {
self.pushTitleLabel?.text = t
}
But I still have to navigate away from the tab and back again to have the text updated, which viewWillAppear() takes care of.