Now I need to get the user opening the APP's time,and compare the time to the last time, if the time is more than 24 hours, just to remind the user of updating App. Who knows the Objective-C code about this? Please help me .Thank U very much!
Create a NSDate member variable (i.e NSDate *startDate) in your AppDelegate file. Now in AppDelegate.m class use the below code.
- (void)applicationDidEnterBackground:(UIApplication *)application {
// save the last app opening time, you can save in NSuserdefaults also
startDate = [NSDate date];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
NSDate *now = [NSDate date];
// Returns in seconds
NSTimeInterval timeInterval = [now timeIntervalSinceDate:startDate]
if(timeInterval > (24*3600)) {
// remind the user of updating App here.
}
}
I will suggest to store the values in user defaults , so that if user exits the app even then we can have the data time details. Add the below code in app delegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSDate *dateTimenow=[NSDate date];
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd-MM-yyyy hh:mm"];
NSString *strDateTimeNow=[NSString stringWithFormat:#"%#",[dateFormatter stringFromDate:dateTimenow]];
NSLog(#"now date time: %#",strDateTimeNow);
NSUserDefaults *userdefaults=[NSUserDefaults standardUserDefaults];
if ([userdefaults valueForKey:#"LastAppLaunchTime"]) {
NSString *strPreviousDateTime=[NSString stringWithFormat:#"%#",[userdefaults valueForKey:#"LastAppLaunchTime"]];
NSLog(#"previous date time: %#",strPreviousDateTime);
//Now you can compare current date time with previous date time
//perform task after comparing
}
[userdefaults setValue:strDateTimeNow forKey:#"LastAppLaunchTime"];// saving recent date time details for next time
you can also do this while going in background and coming to foreground, so if app is suspended in background for more than 24 hours then also you can perform your task. I hope this helps.
You can use NSDate:
NSDate* now = [NSDate date];
Save this value as lastTimeOpened and compare during next launch:
if ([now timeIntervalSinceDate:lastTimeOpened] > someTime)
Related
I am working on Alarm module in my app. I have develop code which take date and time input from user and set Event on that particular time in my app.
Also i store information into my local database to display list of alarm set by user.
Now i want to delete entry from database when particular alarm executed (When UILocalNotification displayed into app i want to call database method to delete that entry from db)
I set Notification by this way
NSUserDefaults* preferences = [NSUserDefaults standardUserDefaults];
int notificationCount = [preferences integerForKey:#"notification_count"];
notificationCount++;
NSDate* final_date = [calendar dateFromComponents:final_Components];
UILocalNotification *localNotification = [[UILocalNotification alloc]init];
localNotification.fireDate = final_date;
localNotification.alertBody=titleTextField.text;localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.applicationIconBadgeNumber = 1;
NSDictionary* userInfoDic = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:notificationCount] forKey:#"notification_id"]; localNotification.userInfo = userInfoDic;
localNotification.repeatInterval = 0;
[[UIApplication sharedApplication]scheduleLocalNotification:localNotification];
[preferences setInteger:notificationCount forKey:#"notification_count"];
I used Delegate didReceiveLocalNotification
-(void) application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
NSString *itemName = [notification.userInfo objectForKey:#"notification_id"];
NSLog(#"userInfo is %#",itemName);
databaseObject.deleteNotification(itemName)
}
My problem is "didReceiveLocalNotification" only call in 2 case
1) When user using app (app in foreground).
2) when notification displayed and user click on notification
But in 3rd case when app is in background mode and notification displayed and if user don't click on notification Or second case is open app directly clicking on app icon or user clear notification at that time didReceiveLocalNotification delegate is not get called..
Is there any way to detect Notification fire in all case or any other method by using i can detect that notification has been fire and then i will execute my delete method.
Any help is appreciated
Thank you
Yes, you are right, you won't know the information of the notification if your notification fires while your app is suspended/terminated and user didn't tap the notification to launch/active your app.
The only way to do this is to calculate the time every time your app is running and reschedule notifications and update your database.
For millisecond calculation:
NSInteger myMillisecond; //assume it exists
const NSTimeInterval oneSecondAsMilliseconds = 1000.0;
NSTimeInterval myTimeInterval = myMillisecond/oneSecondAsMilliseconds;
NSDate *currentDate = [NSDate date];
NSTimeInterval currentTimeStamp = [currentDate timeIntervalSince1970];
if (myTimeInterval > currentTimeStamp) {
//myTimeInterval is a later time than now
}
How would I get the length of time a phone was locked if I wanted to use it to increment a timer progress view when the phone was resumed, or schedule a notification to fire when the phone was still locked?
Implement the UIApplicationDelegate method applicationWillResignActive: and applicationDidBecomeActive:.
You will have to store the current time when the former is called and calculate the difference when the latter is called. Specifically, in your application delegate:
#define TIMESTAMP_KEY #"timestamp"
- (void)applicationWillResignActive:(UIApplication *)application
{
NSInteger *timestamp = [[NSDate date] timeIntervalSince1970];
[[NSUserDefault standardUserDefaults] setInteger:timestamp forKey:TIMESTAMP_KEY];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
NSInteger *newTimestamp = [[NSDate date] timeIntervalSince1970];
NSInteger *oldTimestamp = [[NSUserDefault standardUserDefaults] integerForKey:TIMESTAMP_KEY];
NSInteger *secondsPassed = newTimestamp - oldTimestamp;
// Now you can resynch your timer with the secondsPassed
}
I'd like to have a label in my app that gets updated once a day at a specific time (i.e. 12 a.m.). If you could help me out I'd really appreciate it, thanks.
This is what i currently have but it only works if the app is opened between 12 and 1 am.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH"];
NSString *stringDate = [formatter stringFromDate:[NSDate date]];
if ([stringDate isEqualToString:#"00"]) {
NSLog(#"its working");
[self changeLabel];
}
To clarify, I'm trying to change the text of a label once a day. I'd like to have the label update at a specific time like 12 am so that it updates with the start of each new day. I've tried a few ways of doing this but haven't gotten the desired result. If anyone knows of a way to do this I'd appreciate your input.
If you only need to determine the last time the application was opened, you can use NSUserDefaults to save the date and then check that the approprate number of seconds (86400 = 1 day) have passed.
Something along the lines of the following should point you in the right direction:
//gather last time app was opened
NSDate *lastUpdated = [[NSUserDefaults standardUserDefaults] objectForKey:#"app_last_updated"];
//check date is valid
if(lastUpdated)
{
//determine number of seconds that have passed
NSTimeInterval timeInterval = [lastUpdated timeIntervalSinceNow];
//check time interval is greater than 1 day
if(timeInterval > 86400)
{
//update label
}
}
//save current time
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:#"app_last_updated"];
It depends on what you want to do. On iOS, most likely your app is not running in the foreground all the time. So I would just update the label when the application is active in applicationDidBecomeActive:. Then I would create a timer to fire at the specific date/time I want.
For example:
NSDate *d = // create the next date/time
updateTimer_ = [[NSTimer alloc] initWithFireDate: d
interval: 0
target: self
selector:#selector(updateLabel:)
userInfo:nil repeats:NO];
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:updateTimer_ forMode: NSDefaultRunLoopMode];
I know this is an old post but a few days ago I needed just what Dave123 asked and I came up with this solution after searching a lot on the web:
- (void)applicationDidBecomeActive:(UIApplication *)application {
NSLog(#"applicationDidBecomeActive");
self.masterviewController = [[PBMasterViewController alloc] init];
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
NSLog(#"Seconds --------> %.f",[[NSDate date] timeIntervalSinceDate:[[NSUserDefaults standardUserDefaults] objectForKey:#"OLD_DATE"]]);
NSLog(#"old date: %#", [[NSUserDefaults standardUserDefaults] objectForKey:#"OLD_DATE"]);
// 24 hours must elapse between each update check
if ([[NSDate date] timeIntervalSinceDate:[[NSUserDefaults standardUserDefaults] objectForKey:#"OLD_DATE"]] > 86400) {
NSLog(#"Time elapsed since last update is MORE than 1 day. Check for updates.");
[self.masterviewController checkForUpdates];
} else {
NSLog(#"Time elapsed since last update is LESS than 1 day. Don't check for updates.");
}
// Here I convert the seconds into hours with two decimals, if you want to show the time elapsed in a UILabel
NSString *stringCheckInterval = [NSString stringWithFormat:#"%.02f hours since last update", [[NSDate date] timeIntervalSinceDate:[[NSUserDefaults standardUserDefaults] objectForKey:#"OLD_DATE"]] / 60 / 60];
NSLog(#"%#", stringCheckInterval);
}
is there someone that has the app opened form more than 24h??
Anyway, you can simply use an NSTimer with 86400 as delay time.
When you start the app, set up a timer that will fire at 12:00:01 AM and update your label.
iam getting some date and time like appointment time. i want to remind the user before to that particular time.i googled and got some knowledge but still in small confusion where to write my code shall i in application entered back ground method and i have to use alert views or any other .please help me.
NSString *today=[NSString stringWithFormat:#"%# %#",appDelegate.appointmentDate,appDelegate.timeStart1];
NSLog(#"%#",today);
NSDateFormatter *format=[[NSDateFormatter alloc]init];
[format setDateFormat:#"MM/dd/yyyy hh:mm a"];
NSDate *date1=[format dateFromString:today];
NSLog(#"%#",date1);
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *datefo1 =[[NSDateComponents alloc]init];
[datefo1 setMinute:1];
[datefo1 setSecond:0];
NSDate *alerttime=[cal dateByAddingComponents:datefo1 toDate:date options:0];
UIApplication* app = [UIApplication sharedApplication];
UILocalNotification* notifyAlarm = [[UILocalNotification alloc]
init];
if (notifyAlarm)
{
notifyAlarm.fireDate = alerttime;
notifyAlarm.timeZone = [NSTimeZone defaultTimeZone];
notifyAlarm.repeatInterval = 0;
notifyAlarm.alertBody = #"you have an appointment in 30 minutes";
[app scheduleLocalNotification:notifyAlarm];
}
i want notification like on top i want to display some alert even my app is running and not running also. but its coming with out any message, where i am going wrong shall i need to use nsnotification center are some thing else. sorry for my poor english.thanks in advance
You're using local notifications, which is a good start, but you should know that local notifications are only displayed if your app is in the background. If your app is running in the foreground when the time comes you will need to display the notification yourself (UIView / UIAlertView).
You can schedule the local notification whenever you want, it really depends what editing you allow the user to do and, therefore, how much you might need to cancel the local notification and schedule a new version.
Few other things:
Consider using 'NSDate -dateByAddingTimeInterval' (it's just less code for your use case)
You're adding a minute to your date, so the alarm will be after the event (and say the appointment is in 30 minutes time ?)
Use NSLocalizedString for any string that will be displayed to the user
In the future, store less data in the appDelegate, that ins't what that class is for :)
I am developing one application in that I want to find application installation date on my device and when update happen that date and time as programmatically.
Not sure if you can find an application installation date but you could save the current date when the application is first ran. Something like this should do the trick
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if (![prefs objectForKey:#"installation_date"]) {
NSDate *now = [NSDate date];
[prefs setObject:now forKey:#"installation_date"];
}
(This code is untested)