I\'m trying to make my app remember which tab was last being viewed before the app quit, so that the app opens up to the same tab when it is next launched. This is the functiona
Here is the Swift 3 solution. Just set the class of your TabBarController to RememberingTabBarController
in the Storyboard
import Foundation
import UIKit
class RememberingTabBarController: UITabBarController, UITabBarControllerDelegate {
let selectedTabIndexKey = "selectedTabIndex"
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
// Load the last selected tab if the key exists in the UserDefaults
if UserDefaults.standard.object(forKey: self.selectedTabIndexKey) != nil {
self.selectedIndex = UserDefaults.standard.integer(forKey: self.selectedTabIndexKey)
}
}
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
// Save the selected index to the UserDefaults
UserDefaults.standard.set(self.selectedIndex, forKey: self.selectedTabIndexKey)
UserDefaults.standard.synchronize()
}
}