Reputation: 1874
I'm making this small game with swift and the game is set up using the viewDidLoad. Each day the game is suppose to be slightly different, but that depends on that the viewDidLoad runs. So let's say a user plays at day 1 and keeps the game active to day 2, the game won't function on day 2 since the viewDidLoad wasn't run. For the game to function properly I need to run the VieDidLoad each time "applicationDidBecomeActive", to make sure it runs as it should.
I've tried to do like this:
func applicationDidBecomeActive(application: UIApplication)
{
myViewController?.viewDidLoad()
}
I also tried to wrap my code that is inside viewDidLoad like this and run it in applicationDidBecomeActive. But that doesn't do it.
override func viewDidLoad()
{
func refreshView()
{
//all the code goes here
}
}
Any idea what I could do?
Upvotes: 2
Views: 9286
Reputation: 1046
I have the same probelm but i solve it with call
self.viewDidLoad()
On my Func I wanna to call my view did load again from it.
Upvotes: 1
Reputation: 14487
viewDidLoad
method not meant to load many times, this will be called only once per lifecycle of viewController
when view first created an loads into memory, and this is not right approach call this again and again.
What you want is possible without loading viewDidLoad
again and again, move your refreshView
method out of viewDidLoad
and call it when required, you can call it once form viewDidLoad
and after that you can call it again when required.
You can respond to application notification
methods like
UIApplicationWillEnterForegroundNotification
or in
UIApplicationDidBecomeActiveNotification
and then figure out do you want to refresh view or not, if you want to refresh view just call your refresView
method.
Your code should look like this
override func viewDidLoad()
{
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "OnAppBecameActive", name: UIApplicationDidBecomeActiveNotification, object: nil)
refreshView()
}
func refreshView()
{
//all the code goes here
}
And add this method as well
func OnAppBecameActive()
{
// Add logic here to check if need to call refresh view method
if needToRefreshView
{
refreshView()
}
}
Upvotes: 2
Reputation: 2052
Set your view controller to listen applicationDidBecomeActive
notifications and run the configuration method when it receives it
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "refreshView:",
name: UIApplicationDidBecomeActiveNotification,
object: nil)
Upvotes: 3