Is there any delegate that fires when I run the iphone application for the first time? - iphone

I need to track the download of a certain iphone application. I tried a lot and found out that we could track it from the AppStore. But i need to track that from my application itself. So please help me to identify the method that fires when the application starts for the first time. Thanks.

There's no specific method that fires only on the 1st application launch. You can set a flag in user defaults on application start - so if the flag is not present then that will mean that application launched for the 1st time:
- (void)applicationDidFinishLaunching:(UIApplication *)application {
if (![[NSUserDefaults standardDefaults] boolForKey:#"AlreadyLaunched"]){
// First launch logic
[[NSUserDefaults standardDefaults] setBool:YES forKey:#"AlreadyLaunched"];
[[NSUserDefaults standardDefaults] synchronize];
}
...
}

But i need to track that from my application itself.
No.
But if you really want to do this you could use something like this:
BOOL hasUsedSpyWareFunctions = [[NSUserDefaults standardUserDefaults] boolForKey:#"SpyWareKey"];
if (!hasUsedSpyWareFunctions) {
[self spyOnUser];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"SpyWareKey"];
}
if you are a Pro in spying you only set the key to YES if the method returned successfully (ie a network connection could be established)

There’s no such an event, at least not one that I know of. But what you want can be trivially done using NSUserDefaults. Simply check for some boolean flag and if it’s not there, it’s a first run and you can set the flag:
NSString *const AlreadyRunKey = #"already-run";
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if (![prefs boolForKey:AlreadyRunKey]) {
[prefs setBool:YES forKey:AlreadyRunKey];
[prefs synchronize];
// do whatever else you want
}

Related

Saving incremental int variable

I need to save a variable that increments every time a user hits a button within the app. I've been trying to do that with NSUserDefaults with no success. Here's the code I'm using:
[[NSUserDefaults standardUserDefaults] setInteger:i++ forKey:#"AppCount"];
When I output this in the log, however, I keep getting 0.
Any help would be greatly appreciated.
Try adding:
[[NSUserDefaults standardUserDefaults] synchronize];
After each time you change the value of your integer.
Quoting Apple's documentation on synchronize:
Writes any modifications to the persistent domains to disk and updates
all unmodified persistent domains to what is on disk.
http://developer.apple.com/library/ios/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html#//apple_ref/occ/instm/NSUserDefaults/synchronize
So with this modification, your final code should look like this:
[[NSUserDefaults standardUserDefaults] setInteger:i++ forKey:#"AppCount"];
[[NSUserDefaults standardUserDefaults] synchronize];
EDIT: Actually on second thought, give this a try:
I think the problem is using i++ assumes that the application will always be able to keep track of the count, and every time you re-enter the application i gets reset.
The following works, I just tested it.
if (![[NSUserDefaults standardUserDefaults] integerForKey:#"AppCount"]) {
[[NSUserDefaults standardUserDefaults] setInteger:i forKey:#"AppCount"];
}else{
[[NSUserDefaults standardUserDefaults] setInteger:[[NSUserDefaults standardUserDefaults] integerForKey:#"AppCount"] + 1 forKey:#"AppCount"];
}
[[NSUserDefaults standardUserDefaults] synchronize];
You can use Static NSUIInteger appCount=0;
in the function user taps increase it value appCount++;
that keeps the value in function calls within the app. after app closing you write it to file.
- (void)viewDidLoad {
[super viewDidLoad];
countFirst= [[NSUserDefaults standardUserDefaults]integerForKey:#"Counter"];
countFirst++;
}
Write this wherever you want to increment.
[[NSUserDefaults standardUserDefaults] setInteger:countFirst++ forKey:#"Counter"];

Count and store a value in xcode

Hello everyone I would have a value for the need to save every time I press a button (count), virtually every time a user presses a button in my app should be pressed to keep count of the times (1,2,3,4, etc. etc.) the problem is that that data would be permanently saved, that is, even when you exit the app or restart the device should be saved on the iphone to find it and increase it reopened after the application.
Is there an easier way to CoreData or SqlLite to do this?
thanks
Here is a sample code:
To store it:
[[NSUserDefaults standardUserDefaults] setInteger: intCount forKey:#"Count"];
[[NSUserDefaults standardUserDefaults] synchronize];
To read it:
intCount = [[NSUserDefaults standardUserDefaults] integerForKey: #"Count"];
The easiest way would be use NSUserDefaults to do this, no need for a bigger data store if it's only an integer.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int buttonCount = 0;
// Do you count somewhere and add to buttonCount
[defaults setObject:[NSNumber numberWithInt:buttonCount] forKey:#"buttonPress"];
and to retrieve to number back just use
int buttonPress = [[[NSUserDefaults standardUserDefaults] objectForKey:#"buttonPress"] intValue];
NSUserDefaults is the solution. Update the stored value in every button click....

Storing preferences in NSUser Defaults to recall later

Been working on some code streamlining and have realised that it would be really helpful if my app had a preferences system.
Now here's how my code works.
A method runs based upon an integer stored in NSUserDefaults
e.g.
if ([[NSUserDefaults standardUserDefaults] integerForKey:#"scifi1"] == 040){
[self spaceDown];
}
else if ([[NSUserDefaults standardUserDefaults] integerForKey:#"scifi1"] == 10040){
[self ctrldown];
[self spaceDown];
}
Now what I want to do is when I exit the view (via a specific button) is to dump the value of #"scifi1" into a new preference, say for example - an integer named #"savedscifi1"
Now I know how to save integers into NSUserDefaults,
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setInteger:VALUEHERE forKey:#"savedscifi1"];
[userDefaults synchronize];
However - I'm not sure how I can substiture in the value of scifi1 instead of (in this case) 'VALUEHERE' - can anyone help with this? I feel it's really simple but I can't help but think I'm being a bit thick...sleep deprived and approaching a deadline! I know I can't just call up #"scifi1"but beyond that....??
NSInteger value = [[NSUserDefaults standardUserDefaults] integerForKey: ...];
[[NSUserDefaults standardUserDefaults] setInteger: value forKey: ...];

First Time Opened Event

In my iPad app, I have a UIAlertView which pops up upon start up, however I only want this to popup the very first time the user starts the application. It's a setup prompt, saying, it's your first time, would you like to setup?
How can I do this? I have heard it's best to write out to a plist file and save a bool value, but how would I tackle this?
Modify the following code to suit your needs; you may put it in your root view controller viedDidLoad method. The code keeps track of the first run of the application, of the number of launches and whether or not the your setup prompt has been shown to the user.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults objectForKey:#"firstRun"]) {
// this is the first run
// store this information
[defaults setObject:[NSDate date] forKey:#"firstRun"];
[defaults setInteger:1 forKey:#"launches"];
[defaults setBool:NO forKey:#"setupPromptHasBeenShown"];
[defaults synchronize];
// now prompt the user to setup the app
// once the the prompt has been shown,
// if the user actually decides to setup the app,
// store this information again, so you will not prompt him/her again
[defaults setBool:YES forKey:#"setupPromptHasBeenShown"];
[defaults synchronize];
}
else{
// this is not the first run
NSInteger daysSinceInstall = [[NSDate date] timeIntervalSinceDate:[defaults objectForKey:#"firstRun"]] / 86400;
NSInteger launches = [defaults integerForKey:#"launches"];
[defaults setInteger:launches+1 forKey:#"launches"];
[defaults synchronize];
}
You could use NSUserDefaults to achieve this with just a few lines of code.
http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html

Best way to check if an iPhone app is running for the first time

I want to check if my iPhone app is running for the first time. I can create a file in the documents folder and check that file to see if this is the first time the app is running, but I wanted to know if there is a better way to do this.
I like to use NSUserDefaults to store an indication of the the first run.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults objectForKey:#"firstRun"])
[defaults setObject:[NSDate date] forKey:#"firstRun"];
[[NSUserDefaults standardUserDefaults] synchronize];
You can then test for it later...
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if([defaults objectForKey:#"firstRun"])
{
// do something or not...
}
Ok what confuses the hell out of me about User Defaults.
WHERE are they stored?
you dont care it varies per iOS/Mac.
you just getVALUE by KEY
setVALUE by KEY + synchronize
iOS/Mac does the rest.
This is the common use case:
Checking for the existence of a value e.g firstRun.
The first time it will NOT EXIST so usually followed by setting the value.
2nd Run
- on next loop it does exist and other use case/else stmt is triggered
---- .h
#interface MyAppDelegate : UIResponder <UIApplicationDelegate>
//flag to denote if this is first time the app is run
#property(nonatomic) BOOL firstRun;
------ .m
#implementation MyAppDelegate
#synthesize firstRun = _firstRun;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//==============
//Check to see if this is first time app is run by checking flag we set in the defaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults objectForKey:#"firstRun"]){
//flag doesnt exist then this IS the first run
self.firstRun = TRUE;
//store the flag so it exists the next time the app starts
[defaults setObject:[NSDate date] forKey:#"firstRun"];
}else{
//flag does exist so this ISNT the first run
self.firstRun = FALSE;
}
//call synchronize to save default - where its saved is managed by iOS - varies by device and iOS/Mac
[[NSUserDefaults standardUserDefaults] synchronize];
//TO TEST: delete the app on the device/simulator
//run it - should be the first run
//close it - make sure you kill it and its not just in the background else didFinishLaunchingWithOptions wont be called
//just applicationDidBecomeActive
//2nd run it should self.firstRun = FALSE;
//=============
//NOTE IMPORTANT IF YOURE ROOTVIEWCONTROLLER checks appDelegate.firstRun then make sure you do the check above BEFORE setting self.window.rootViewController here
self.window.rootViewController = self.navController;
[self.window makeKeyAndVisible];
return YES;
}
---- USING THE FLAG
MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
if (appDelegate.firstRun){
NSLog(#"IS FIRST RUN - Do something: e.g. set up password");
}else {
NSLog(#"FPMyMusicScreenViewController: IS NOT FIRST RUN - Prompt for password");
}
The examples above confused me a bit as they show how to check for it the first time but then mention how to 'check for it later' in the same comment.
The problem is when we find it doesnt exist we immediately create it and synchronize.
So checking for it late actually mean when you RESTART THE APP not in same run as first run.
In your app delegate register a default value:
NSDictionary *defaultsDict =
[[NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithBool:YES], #"FirstLaunch", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsDict];
[defaultsDict release];
Then where you want to check it:
NSUserDefaults *sharedDefaults = [NSUserDefaults standardUserDefaults];
if ([sharedDefaults boolForKey:#"FirstLaunch"]) {
//Do the stuff you want to do on first launch
[sharedDefaults setBool:NO forKey:#"FirstLaunch"];
[sharedDefaults synchronize];
}
You can implement it with the static method below. I think it's better since you can call this method as many times as you like, unlike the other solutions. enjoy: (Keep in mind that it's not thread-safe)
+ (BOOL)isFirstTime{
static BOOL flag=NO;
static BOOL result;
if(!flag){
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"hasLaunchedOnce"])
{
result=NO;
} else
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"hasLaunchedOnce"];
[[NSUserDefaults standardUserDefaults] synchronize];
result=YES;
}
flag=YES;
}
return result;
}
You can use a custom category method isFirstLaunch with UIViewController+FirstLaunch.
- (BOOL)isFirstLaunch
{
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"kFirstLaunch"]) {
return YES;
}
else {
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"kFirstLaunch"];
[[NSUserDefaults standardUserDefaults] synchronize];
return NO;
}
}
And when you need to use it in controller
BOOL launched = [self isFirstLaunch];
if (launched) {
//if launched
}
else {
//if not launched
}
Use NSUserDefaults. If the sharedDefault has a key for your app, its run before. Of course, you'll have to have the app create at least one default entry the first time the app runs.
Swift:
var isFirstLaunch: Bool {
get {
if (NSUserDefaults.standardUserDefaults().objectForKey("firstLaunchDate") == nil) {
NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey: "firstLaunchDate")
NSUserDefaults.standardUserDefaults().synchronize()
return true
}
return false
}
}
Another tip:
When using NSUserDefaults, these settings will be wiped if the app is ever deleted. If for some reason you require these settings to still hang around, you can store them in the Keychain.