我正在开发一个应用程序,该应用程序中,当通过主屏幕按钮将其推入后台时,应该启动计时器,并且当应用程序返回到前台并且计时器经过一定时间后,应该执行一些操作。

我的问题是

  • 我的应用转到以下位置时如何处理事件
    背景/前景?
  • 是否有特殊方法或其他技术?

  • 非常感谢。

    最佳答案

    可能的实现如下所示:

    #define YOUR_TIME_INTERVAL 60*60*5   //i.e. 5 hours
    
    - (void)applicationDidEnterBackground:(UIApplication *)application
    {
        //... your oder code goes here
    
        NSNumber *timeAppClosed = [NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults timeAppClosed forKey:@"time.app.closed"];
        [defaults synchronize];
    }
    


    - (void)applicationWillEnterForeground:(UIApplication *)application
    {
        NSNumber *timeAppClosed = [[NSUserDefaults standardUserDefaults] valueForKey:@"time.app.closed"];
        if(timeAppClosed == nil)
        {
            //No time was saved before so it is the first time the user
            //opens the app
        }
        else if([[NSDate date] timeIntervalSinceDate:[NSDate dateWithTimeIntervalSince1970:[timeAppClosed doubleValue]]] > YOUR_TIME_INTERVAL)
        {
            //Place your code here
        }
    }
    

    10-08 06:11