2014-01-16 42 views

回答

0

如果您的應用已移至後臺,則還會發送DidEnterBackground消息。您可以在WillResignActive之後的一小段延遲後檢查是否發送了兩封郵件。

編輯:選中該代碼

@interface HSAppDelegate() 
{ 
    BOOL _enteredBackground; 
} 

@end 

@implementation HSAppDelegate 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    NSLog(@"%s", __PRETTY_FUNCTION__); 
    _enteredBackground = NO; 
    _window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; 
    _window.rootViewController = [HSViewController new]; 
    [_window makeKeyAndVisible]; 

    return YES; 
} 

- (void)applicationWillResignActive:(UIApplication *)application 
{ 
    NSLog(@"%s", __PRETTY_FUNCTION__); 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     if (!_enteredBackground) 
     { 
      // Do whatever you want here. 
     } 
     else 
     { 
      // This won't get called until the app comes back to foreground. 
     } 
    }); 
} 

- (void)applicationDidEnterBackground:(UIApplication *)application 
{ 
    NSLog(@"%s", __PRETTY_FUNCTION__); 
    _enteredBackground = YES; 
} 

- (void)applicationWillEnterForeground:(UIApplication *)application 
{ 
    NSLog(@"%s", __PRETTY_FUNCTION__); 
    _enteredBackground = NO; 
} 

- (void)applicationDidBecomeActive:(UIApplication *)application 
{ 
    NSLog(@"%s", __PRETTY_FUNCTION__); 
} 

@end 
+0

謝謝。關鍵是我需要在WillResignActive中執行操作,我不能等待DidEnterBackground。 – shannoga

+0

我已經爲你添加了示例代碼。希望它能幫助你指出正確的方向。它工作的原因是在同一隊列中調用'dispatch_async'會強制該塊被調用而不是下一個運行循環。 –

相關問題