I want to display the date, the app I make was opened for the first time in view (which is the only view in the whole app for now).
What kind of object do I use best in my view to display the date and how do I get it in there?
I want to display the date, the app I make was opened for the first time in view (which is the only view in the whole app for now).
What kind of object do I use best in my view to display the date and how do I get it in there?
In your AppDelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
if(![[NSUserDefaults standardUserDefaults] objectForKey:@"firstOpenDate"])
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[[NSUserDefaults standardUserDefaults] setObject:[dateFormatter stringFromDate:[NSDate date]] forKey:@"firstOpenDate"];
}
NSLog(@"First Opened: %@",[[NSUserDefaults standardUserDefaults] objectForKey:@"firstOpenDate"]);
return YES;
}
Simply change the setDateStyle:NSDateFormatterLongStyle
if you want other formats. You can query NSUserDefaults
from anywhere.
In ViewController.m
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hi. You first opened the app on" message:[[NSUserDefaults standardUserDefaults] objectForKey:@"firstOpenDate"] delegate:nil cancelButtonTitle:@"Thanks" otherButtonTitles:nil];
[alert show];
}
On first launch, check to see if you've saved a date to user defaults using objectForKey. If not, save today's date
[NSDate date]
To user defaults using setObject:forKey:
Then fall into code that reads the saved date and compares to see how many days have past between that date and today. Take a look at the NSCalendar method components:fromDate:toDate:options
You might want to do a search on "Performing Calendar Calculations" in Xcode and read the resulting chapter.