Reputation: 65
I am using the following code to detect whether the app is running for the first time:
// Detect First Launch
let firstLaunch = NSUserDefaults.standardUserDefaults().boolForKey("FirstLaunch")
if firstLaunch {
print("Not first launch.")
Show()
}
else {
print("First launch, setting NSUserDefault.")
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "FirstLaunch")
}
I am using the following function to show the ViewController:
func Show(){
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier(“myViewController”) as! MyViewController
self.window?.rootViewController?.presentViewController(vc, animated: true, completion: nil)
}
I put both code under: func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
However, when I build and run the app, the initial view controller is shown as if nothing happened. I want “myViewController” to be shown FIRST (during the app’s FIRST EVER LAUNCH on the device.) After that first launch, however, the “myViewController” won’t be shown anymore, unless the user uninstalls and freshly reinstalls the app.
Does anyone know how to do it?
Upvotes: 0
Views: 375
Reputation: 1786
Since you want to show the custom screen on first launch and then dismiss it, I would run this code in your normal root VC's viewWillAppear(animated:Bool)
method
EDIT:
Yes, you will have to modify the code a bit. For example, like so:
func Show(){
guard let sb = storyboard else { return }
let vc = sb.instantiateViewControllerWithIdentifier(“myViewController”) as! MyViewController
navigationController?.presentViewController(vc, animated: true, completion: nil)
}
Upvotes: 1
Reputation: 3894
After setting the value to user defaults, you have to save it using the synchronize
method. This method is invoked periodically buy the system, but if you didn't synchronize before it was called, your value isn't saved.
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "FirstLaunch")
NSUserDefaults.standardUserDefaults().synchronize()
Documentation of synchronize
from to Apple docs :
Writes any modifications to the persistent domains to disk and updates all unmodified persistent domains to what is on disk.
Discussion
Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.
Upvotes: 0