在我的应用程序中,我有一个沿bezierPath设置动画的CALayer数组。当我关闭并重新打开应用程序时,我的图层没有设置动画,并且与关闭应用程序之前的位置不同。我实现了两种方法,pauseLayer和resumeLayer,当我在应用程序内部使用两个按钮触发它们时,它们可以工作,但是在关闭应用程序后它们将无法工作。代码如下

   - (void)pauseLayers{

    for(int y=0; y<=end;y++)
    {



        CFTimeInterval pausedTime = [car[y] convertTime:CACurrentMediaTime() fromLayer:nil];
        car[y].speed = 0.0;
        car[y].timeOffset = pausedTime;

         standardUserDefaults[y] = [NSUserDefaults standardUserDefaults];


        if (standardUserDefaults[y]) {
            [standardUserDefaults[y] setDouble:pausedTime forKey:@"pausedTime"];
            [standardUserDefaults[y] synchronize];
        }


        NSLog(@"saving positions");


        }


}

-(void)resumeLayers

{




    for(int y=0; y<=end;y++)
    {




        standardUserDefaults[y] = [NSUserDefaults standardUserDefaults];
        car[y].timeOffset = [standardUserDefaults[y] doubleForKey:@"pausedTime"];

    CFTimeInterval pausedTime = [car[y] timeOffset];
    car[y].speed = 1.0;
    car[y].timeOffset = 0.0;
    car[y].beginTime = 0.0;

    CFTimeInterval timeSincePause = [car[y] convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    car[y].beginTime = timeSincePause;
        }


}

最佳答案

- (void)applicationDidEnterBackground:(UIApplication *)application {

 mosquitosViewController *mvc = [[mosquitosViewController alloc] init];
  [mvc pauseLayers];

  }

上面您尝试执行的操作的问题在于,您正在创建 View Controller 的全新实例,而不是在屏幕上显示的实例。这就是为什么在发送pauseLayers消息时什么也没有发生的原因。

您应该做的就是注册,以接收有关您的应用何时进入和退出后台的通知,并在通知到达时调用适当的方法(pauseLayersresumeLayers)。

您应该在mosquitosViewController实现中的某处添加以下代码(我通常在viewDidLoad中这样做):
// Register for notification that app did enter background
[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(pauseLayers)
                                      name:UIApplicationDidEnterBackgroundNotification
                                      object:[UIApplication sharedApplication]];

// Register for notification that app did enter foreground
[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(resumeLayers)
                                      name:UIApplicationWillEnterForegroundNotification
                                      object:[UIApplication sharedApplication]];

10-02 22:13