2011-07-22 56 views
5

在我的應用程序中,我有一個CALayer數組,我沿着bezierPath動畫。當我關閉並重新打開應用程序時,我的圖層不是動畫,並且與關閉應用程序之前沒有相同的位置。我已經實現了兩種方法,pauseLayer和resumeLayer,它們在我的應用程序中使用兩個按鈕觸發它們時起作用,但在關閉應用程序後它們不起作用。該代碼是以下如何從多任務回來後恢復CAAnimation

- (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; 
     } 


} 
+0

是否在應用程序進入後臺時調用NSLog? – MiguelB

+0

是的。這是奇怪的事情:( –

+0

向我顯示應用程序委託方法,你叫pauseLayers和resumeLayers。 – MiguelB

回答

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

{

NSLog(@"1"); 
mosquitosViewController *mvc = [[mosquitosViewController alloc] init]; 
[mvc pauseLayers]; 

/* 
Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 
*/ 

}

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

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

    } 

與你正在嘗試上面做的問題是,你正在創建一個完全新的實例你的視圖控制器,這是不是在屏幕上顯示的。這就是爲什麼當您發送pauseLayers消息時沒有任何反應。

你應該做的是註冊接收通知,告知你的應用何時進入並來自後臺,並在通知到達時調用相應的方法(pauseLayersresumeLayers)。多任務處理後

// 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]];