Reputation: 427
I have been researching this for 2 hours and I found a very similar question that was answered by Zaid Pathan. Unfortunately, when I used the code that Zaid shared in my own app, I do not get the result I expect. Here is the code:
override func viewDidLoad() {
super.viewDidLoad()
println("Launched")
func isAppAlreadyLaunchedOnce()->Bool{
let defaults = NSUserDefaults.standardUserDefaults()
if let isAppAlreadyLaunchedOnce = defaults.stringForKey("isAppAlreadyLaunchedOnce"){
println("App already launched")
return true
}else{
defaults.setBool(true, forKey: "isAppAlreadyLaunchedOnce")
println("App launched first time")
return false
}
}
I added the println("Launched")
so I could see in the log that the code had executed. That works. However, the println("App already launched")
and/or println("App launched first time")
do not execute. Any suggestions?
Upvotes: 0
Views: 1265
Reputation: 13537
You can identified weather application luanch first time or not using below method.
For Objective C
if ([self isFirstLuanch]) {
NSLog(@"First lunch");
}else{
NSLog(@"No a first lunch");
}
-(BOOL) isFirstLuanch{
if (![[NSUserDefaults standardUserDefaults] boolForKey:@"HasLaunchedOnce"]){
return NO;
}else{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"HasLaunchedOnce"];
[[NSUserDefaults standardUserDefaults] synchronize];
return YES;
}
}
For swift 4.0
if isFirstLuanch(){
print("First lunch")
}else{
print("No a first lunch")
}
func isFirstLuanch()-> Bool{
if UserDefaults.standard.bool(forKey: "isAppAlreadyLaunchedOnce") {
return false
}else{
UserDefaults.standard.set(true, forKey: "isAppAlreadyLaunchedOnce")
return true
}
}
Upvotes: 1
Reputation: 783
You should call the synchronize() to save data to userdefaults.
defaults.setBool(true, forKey: "isAppAlreadyLaunchedOnce")
defaults.synchronize()
Upvotes: 1
Reputation: 11555
Yo created function in function. Either move the isAlreadyLaunchedOnce
in the scope (to the same level as viewDidLoad
) and call it from viewDidLoad
or modify the code like this:
override func viewDidLoad() {
super.viewDidLoad()
println("Launched")
let defaults = NSUserDefaults.standardUserDefaults()
if let isAppAlreadyLaunchedOnce = defaults.stringForKey("isAppAlreadyLaunchedOnce"){
println("App already launched")
// do something
} else {
defaults.setBool(true, forKey: "isAppAlreadyLaunchedOnce")
println("App launched first time")
// do something
}
}
Upvotes: 2