[英]ios How to fetch App launch time?
現在,我需要讓用戶打開APP的時間,並將時間與上次時間進行比較(如果時間超過24小時),只是要提醒用戶更新App。 誰知道有關此的Objective-C代碼? 請幫助我。非常感謝你!
在AppDelegate文件中創建一個NSDate成員變量(即NSDate * startDate)。 現在在AppDelegate.m類中,使用以下代碼。
- (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.
}
}
我建議將值存儲在用戶默認值中,以便即使用戶退出應用程序,我們也可以獲取數據時間詳細信息。 在應用程序委托中添加以下代碼- (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
您也可以在后台進入前台時執行此操作,因此,如果應用在后台暫停了24小時以上,那么您也可以執行任務。 我希望這有幫助。
您可以使用NSDate:
NSDate* now = [NSDate date];
將該值另存為lastTimeOpened並在下次啟動時進行比較:
if ([now timeIntervalSinceDate:lastTimeOpened] > someTime)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.